2013-03-22 58 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