2013-03-22 69 views
4

我已成功配置Spring自动装配,除了java.util.Properties的实例之外的所有内容。Spring Autowire属性对象

当我自动装配一切与注释:

@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,如果我尝试它采用了一种很好的老式二传手法,Spring很高兴地接通了它:

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

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

回答

8

看起来您正尝试在第一种情况下调用setter方法。当你在一个bean元素内创建一个属性元素时,它将使用setter注入来注入这个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"/> 

应该然后正确自动装配。

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

+1

谢谢=现在为我工作,id =“消息”添加到属性标记。 – NickJ 2013-03-22 17:46:53