@Autowired
private String defaultLanguage;
当我尝试@Autowire
defaultLanguage
类的CountryBean
字段时,如下所示:
<beans:bean id="countryBean" class="geoapp.CountryBean">
<beans:property name="defaultLanguage" value="English" />
</beans:bean>
我收到此错误:
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.CountryBean.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)}:
当它显示No matching bean of type [java.lang.String] found for dependency
时,我想知道是否还需要其他一些内容让它知道价值English
是String
?
答案 0 :(得分:2)
由于您是通过xml显式指定属性值,因此无需使用自动连线注释。
答案 1 :(得分:1)
您没有正确使用自动装配功能。 你可以:
<beans:property ... />
并为类@Autowired
注释在Spring上下文中自动查找具有您的属性 class 的现有bean(在您的情况下为String
)答案 2 :(得分:0)
其他答案是正确的,但为了澄清事情,* .xml文件中定义的那些bean在任何@type注释被处理之前被处理。因此,对于您的示例,在处理属性“defaultLanguage”之前处理bean“CountryBean”,使依赖项为null。
答案 3 :(得分:0)
还有另外一个'其他答案是正确的',但这是你的另一个消息 - 春天会自动为你设置枚举,所以如果你有一个语言的枚举,你的bean定义有类似“,你会得到一个类型安全的枚举,而不是一个字符串。
答案 4 :(得分:0)
如果要自动装配属性,则需要为该defaultLanguage String创建一个新bean。然后将bean的名称和字段名称等同起来。