2011-04-14 45 views
1

我想根據來自屬性file.how的請求獲取特定值來執行此操作嗎?在運行時從屬性文件中讀取

我有以下春天configuration.i要設置Exprops值按該請求,並得到相應的值從屬性文件

<bean id="Prop" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location"> 
     <value>classpath:ErrorMessage.properties</value> 
    </property> 
</bean> 

<bean id="PropertiesBean" class="com.util.PropertiesUtil"> 
    <property name="Exprops" value="${EXampleExceptiion}"></property> 
</bean> 
+0

PropertyPlaceholderConfigurer僅用於配置您的應用程序,以某種方式靜態,它不打算被你的應用程序調用。 – Ralph 2011-04-14 15:56:00

+0

我想你必須自己實現這個。據我所知,Spring沒有提供具體的支持。 – 2011-04-14 21:31:21

+0

感謝@ Ralph,@ Benjamin..can任何一個都可以爲我提供實現,從PropertyPlaceholderConfigurer中讀取文件可以用來設置運行時的值 – Vish 2011-04-15 05:37:10

回答

9

使用PropertiesFactoryBean在一個Bean注入Properties

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

這提供了Properties對象/豆,其可以將其姓名myPropertiesBean下在任何豆(<property name="x" ref="myPropertiesBean"/>)被注入。

另外Spring提供了UTIL命名空間(因爲Spring 2.5中): 在那裏,你可以寫PropertyFactoryBean定義短一點:

<util:properties id="myPropertiesBean" 
location="classpath:ErrorMessage.properties"/> 

@see Spring Reference Chapter C.2.2.3.

+0

Thanks @ Ralph,這看起來更好 – Vish 2011-04-15 09:52:01

+0

我們可以在同一個PropertiesFactoryBean中寫入多個屬性嗎?由不同的Spring beans使用 – Vish 2011-04-15 10:56:31

+0

@Vish:PropertiesFactoryBean提供了java.util.Properties - 它們是多個屬性! (或者你的意思是,多個properties文件)。是的,你可以在不同的bean中使用它們(每個都會得到它的一個java.util.Properties實例,但是具有相同的鍵/值) – Ralph 2011-04-15 12:47:29

1

所有使用下面這樣做以編程方式

XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml")); 
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); 
cfg.setLocation(new FileSystemResource("jdbc.properties")); 
cfg.postProcessBeanFactory(factory);