2015-04-24 43 views
0

考慮這個例子加載屬性文件是給怪異的行爲

public class EmailSender {  
private Properties emailProperties; 
public Properties getEmailProperties() { 
    return emailProperties; 
    } 

    public void setEmailProperties(Properties emailProperties) { 
    this.emailProperties = emailProperties; 
    } 

applicationContext.xml我有類似

<bean name="emailSender" class="com.api.email.EmailSender"> 
    <property name="emailProperties" value="classpath*:email.properties"/> 
</bean> 

當調試什麼獲取設置,我看到

enter image description here

如何爲加載?

回答

1

我不得不注入另一個bean它知道如何解決屬性。以下爲我工作

<bean id="emailProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="location" value="classpath:email.properties"/> 
</bean> 

<bean name="emailSender" class="com.api.email.EmailSender"> 
    <property name="emailProperties" ref="emailProperties"/> 
</bean> 
0

您分配屬性文件的方式似乎不完整。我通常使用util函數。添加到您的背景下xml文件的命名空間:

的xmlns:UTIL = 「http://www.springframework.org/schema/util」

然後宣告你的屬性文件:

<util:properties 
    id="emailProperties" 
    location="classpath:/app.properties"/> 

而且設置bean值:

<bean name="emailSender" class="com.api.email.EmailSender"> 
    <property name="emailProperties" ref="emailProperties"/> 
</bean> 

也許事情已經在Spring 4被簡化了,但是這是你怎麼做3和更早版本。它比使用org.springframework.beans.factory.config.PropertiesFactoryBean短一點點。

+0

我有二傳手,更新我的問題 – daydreamer

+0

打我吧:)! –

0

另一種解決方案:

<context:property-placeholder location="classpath*:email.properties" /> 

<bean class="com.test.EmailSender" > 
    <property name="prop1" value="${mail.prop1}" /> 
    <property name="prop2" value="${mail.prop2}" /> 
</bean> 

-

public class EmailSender { 

    private String prop1; 
    private String prop2; 

    public String getProp1() { 
     return prop1; 
    } 

    public void setProp1(String prop1) { 
     this.prop1 = prop1; 
    } 

    public String getProp2() { 
     return prop2; 
    } 

    public void setProp2(String prop2) { 
     this.prop2 = prop2; 
    } 
}