Could not autowire method

2019-05-01 21:01发布

I am getting this error

org.springframework.beans.factory.BeanCreationException: 
Could not autowire method:

This is my spring's xml configuration.

<bean ...>   
...
    <property name="InfoModel" ref="InfoModel"></property>
</bean>

Here is my code where I am autowiring this in Java class

  private InfoModel infoModel;

  @Autowired
  public void setInfoModel(InfoModel infoModel) {
    this.infoModel= infoModel;
  }

Am I missing something. I suspect that I should make an Interface of InfoModel in order to make it autowire?

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.model.InfoModel] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:547)

4条回答
狗以群分
2楼-- · 2019-05-01 21:25

if you do @Autowired you don't need to mark it as property in xml. just declare InfoModel as bean in XML and remove property from xml for you bean where you have injected InfoModel

Summing up

1 You need a bean definition in your XML for InfoModel

2 You need to remove property from XML

3 Make sure you have made your context annotation driven by adding

<context:annotation-config />
查看更多
Lonely孤独者°
3楼-- · 2019-05-01 21:33

Did you properly annotate your InfoModel class with a Type Level Annotation such @Component, @Service, or @Repository. All of them are very similar. If your InfoModel is not properly annotated you will receive this famous "No matching bean..." error. Try annotating your InfoModel class with @Component to look like this:

@Component
public class InfoModel {
  // code
}
查看更多
▲ chillily
4楼-- · 2019-05-01 21:37

I think you should write @Autowired before the private Info.... Declaration. and remove entry from the xml as mentioned by jigar.

查看更多
smile是对你的礼貌
5楼-- · 2019-05-01 21:39

If the stack trace says there are no matching beans of said type, then that's what wrong.

Add the InfoModel bean to the spring application context, e.g. by declaring the bean in the same xml configuration:

<bean id="InfoModel" class="com.model.InfoModel" />

btw. you shouldn't capitalize the first letter of the bean identifier, follow the same naming convention as for variables, ie. lowerCamelCase. Autowiring and explicitly injecting the dependency is also redundant.

查看更多
登录 后发表回答