Could not autowire method

左心房为你撑大大i 提交于 2019-12-22 06:29:27

问题


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)

回答1:


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 />



回答2:


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.




回答3:


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




回答4:


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
}


来源:https://stackoverflow.com/questions/8635861/could-not-autowire-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!