开发者

Why doesn't Autowiring work for this Spring MVC String bean property?

@Autowired
private String defaultLanguage;

When I try to @Autowire the defaultLanguage field of the CountryBean class as follows:

<beans:bean id="countryBean" class="geoapp.CountryBean">
    <beans:property name="defaultLanguage" value="English" />
</beans:bean>

I get this error:

Error creating bean with name 'CountryBean': 
Injection of autowired dependencies failed; 
nested exception is 
org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: 
private java.lang.String geoapp.Count开发者_如何学PythonryBean.defaultLanguage; 
nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No matching bean of type [java.lang.String] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for 
this dependency. 
Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}:

When it says No matching bean of type [java.lang.String] found for dependency, I wonder if there's something else I need to say to let it know that the value English is a String?


Since you are explicitly specifying the property value via xml, there is no need to have the AutoWired annotation.


You are not using the autowire feature properly. You can either:

  • Use the <beans:property ... /> in the XML and add a setter for the property in the class
  • Use the @Autowired annotation that automatically looks in the Spring context for an existing bean that has your property class (in your case, String)


The other answers are correct, but to clarify things, those beans defined in the *.xml files are processed before any @ type annotations get processed. So for your example, the bean "CountryBean" is processed before the property "defaultLanguage" is processed, leaving the dependency null.


Yet another 'the other answers are correct', but here's another tidbit for you -- Spring will automatically set enums for you, so if you had an enum of languages and your bean definition had something like ", you'd get a type safe enum in there, instead of a String.


If you want autowiring your property, you need to make a new bean for that defaultLanguage String. Then equate the bean's name and field's name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜