4

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

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

@Autowired private SomeObject someObject;

它工作得很好。

但是当我尝试这个时:

@Autowired private Properties messages;

使用此配置:

<bean id="mybean" class="com.foo.MyBean" >
  <property name="messages">
    <util:properties location="classpath:messages.properties"/>
  </property>
</bean>

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

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?

Wheras,如果我用一个很好的老式 setter 方法尝试它,Spring 会非常高兴地连接它:

public void setMessages(Properties p) {   //this works
  this.messages = p;
}

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

4

1 回答 1

8

看起来您正试图在第一种情况下调用 setter 方法。当您在 bean 元素中创建属性元素时,它将使用 setter injection 来注入 bean。(您的情况下没有设置器,因此会引发错误)

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

<property name="messages">
    <util:properties location="classpath:messages.properties"/>
</property>

从bean定义中,这将尝试调用一个setMessages方法。

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

<bean id="mybean" class="com.foo.MyBean" />
<util:properties location="classpath:messages.properties"/>

然后它应该正确地自动接线。

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

于 2013-03-22T17:21:47.853 回答