Spring Autowire属性对象

Nic*_*ckJ 4 java spring autowired

我已成功为除了java.util.Properties实例之外的所有内容配置了Spring自动装配.

当我使用注释自动装配其他所有内容时:

@Autowired private SomeObject someObject;
Run Code Online (Sandbox Code Playgroud)

它工作得很好.

但是,当我尝试这个:

@Autowired private Properties messages;
Run Code Online (Sandbox Code Playgroud)

使用此配置:

<bean id="mybean" class="com.foo.MyBean" >
  <property name="messages">
    <util:properties location="classpath:messages.properties"/>
  </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

我收到错误(仅限相关行):

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mybean' defined in class path resource [application.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'messages' of bean class [com.foo.MyBean]: Bean property 'messages' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Run Code Online (Sandbox Code Playgroud)

Wheras,如果我用一种老式的setter方法尝试它,Spring非常愉快地连接它:

public void setMessages(Properties p) {   //this works
  this.messages = p;
}
Run Code Online (Sandbox Code Playgroud)

尝试自动装配属性对象时,我做错了什么?

cow*_*wls 8

看起来你试图在第一种情况下调用setter方法.在bean元素中创建一个property元素时,它将使用setter注入来注入bean.(在你的情况下你没有一个setter所以它会抛出一个错误)

如果你想自动装配它删除这个:

<property name="messages">
    <util:properties location="classpath:messages.properties"/>
</property>
Run Code Online (Sandbox Code Playgroud)

从bean定义,因为这将尝试调用setMessages方法.

相反,只需将上下文文件中的属性bean分别定义为MyBean:

<bean id="mybean" class="com.foo.MyBean" />
<util:properties location="classpath:messages.properties"/>
Run Code Online (Sandbox Code Playgroud)

然后它应该正确地自动装配.

请注意,这也意味着您可以将此添加@Autowired private Properties messages;到任何Spring托管bean,以在其他类中使用相同的属性对象.