Java 自动连线属性不工作,但自动连线设定器工作?
我在Spring 3.2.2项目中有以下bean类:Java 自动连线属性不工作,但自动连线设定器工作?,java,spring,Java,Spring,我在Spring 3.2.2项目中有以下bean类: @Service public class PropertyFacade { // This DOES NOT work @Autowired private String propertyFileName; // This DOES work // @Autowired // public void setPropertyFileName( String propertyFileName ) { //
@Service
public class PropertyFacade {
// This DOES NOT work
@Autowired
private String propertyFileName;
// This DOES work
// @Autowired
// public void setPropertyFileName( String propertyFileName ) {
// this.propertyFileName = propertyFileName;
// }
我的spring配置文件包含以下内容:
<context:component-scan base-package="org.sperbolink.utility" />
<context:component-scan base-package="org.sperbolink.facade" />
<bean id="propertyFacade" class="org.sperbolink.facade.PropertyFacade" >
<property name="propertyFileName" value="test-properties.inf" />
</bean>
出于某种原因,当我尝试自动关联属性时,会出现错误:
springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String org.sperbolink.facade.PropertyFacade.propertyFileName; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
但是,当我自动连接setter时,一切正常。为什么属性自动布线不起作用?异常消息准确地告诉您问题所在: 您没有在任何地方定义
propertyFileName
bean。
您只需要在beanpropertyFacade
中定义属性propertyFileName
。如果你没有二传手,这是行不通的
通过设置,propertyFileName
valuetestproperties.inf
将自动注入propertyFacade
类中的相应字段。此处不需要@Autowire
注释
当您想要将(某个已定义的)
注入特定字段时,可以使用带字段的@Autowire
。这不应与使用
混用
阅读更多信息。您不能自动关联字符串和基本值。Spring不支持这一点。这就是基于现场的自动布线不起作用的原因
当您取消注释基于属性的自动连接时,您会立即使用XML配置覆盖它,并在其中注入特定值-这就是为什么它会以这种方式工作。仅当setter未注释时<代码>需要一个setter。另一个选项是构造函数注入,它可以自动连接,也可以在bean配置中指定:。当然,这也可以应用于propertyFacade,使您能够创建一个具有真实、可用构造函数的类,您可以使用该构造函数进行测试,但也可以在CDI容器中使用
springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String org.sperbolink.facade.PropertyFacade.propertyFileName; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.