我已经为除 java.util.Properties 实例之外的所有内容成功配置了 Spring Autowiring 。
当我使用注释 Autowiring 其他所有内容时:
@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;
}
尝试 Autowiring 属性对象时我做错了什么?
最佳答案
看起来您正在尝试在第一种情况下调用 setter 方法。当您在 bean 元素内创建属性元素时,它将使用 setter 注入(inject)来注入(inject) bean。 (您的情况下没有 setter ,因此会引发错误)
如果你想 Autowiring 它删除这个:
<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"/>
然后它应该会正确地 Autowiring 。
请注意,这也意味着您可以添加:@Autowired private Properties messages;
到任何 Spring 托管的 bean,以便在其他类中使用相同的属性对象。
关于java - Spring Autowire 属性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15576303/