2012-08-07 57 views
1

我有兩個屬性文件:部署與Maven和春季不同環境

environment.properties: 
- project.host.db3.database.name=oracle 

application.properties: 
- database.name=${project.host.db3.database.name} 

第一個代表環境變量,第二個屬性,以在彈簧項目中使用,在這種配置我嘗試設置environment.properties但當然這是行不通的:

<bean id="systemPropertiesLoader" 
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> 
     <property name="targetObject" value="#{@systemProperties}" /> 
     <property name="targetMethod" value="putAll" /> 
     <property name="arguments"> 
    <util:properties location="classpath:environment.properties" /> 
</property> 
</bean> 

<bean id="propertyPlaceholderConfigurer" 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
depends-on="systemPropertiesLoader"> 
<property name="locations"> 
    <list> 
     <value>classpath:application.properties</value> 
    </list> 
</property> 

<!-- bean using database.name --> 

是否可行?如果沒有,怎麼辦人在他們的項目無關的特性(如database.name),和只有一個文件(戰爭,罐子等)被部署?

+0

爲什麼你不能直接使用environment.properties? – yorkw 2012-08-07 21:57:15

+0

@ yorkw,我開始使用我自己的屬性,後來學會了我應該從另一個屬性文件中提供它們,但我認爲我應該將我的屬性名稱與環境屬性隔離開來 – user311174 2012-08-08 06:36:01

回答

0

好吧,看來它是可行的,只要你定義你的屬性是這樣定義的豆XML:

<bean id="propertyPlaceholderConfigurer" 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
depends-on="systemPropertiesLoader"> 

但是,如果你曾經嘗試從一個servlet訪問屬性:

this.getClass().getClassLoader().getResourceAsStream("application.properties"); 

沒準你會得到這樣的:

bad port configuration: ${project.host.db3.database.port} 
java.lang.NumberFormatException: For input string: "${project.host.db3.database.port}" 

在回答yorkw,現在我可以有相同的WA R鍵在幾個環境中部署和配置與-Denvironment =開發主機,這樣我就可以部署一個屬性文件的開發,生產等,並簡單地使用:

<bean id="systemPropertiesLoader" 
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> 
     <property name="targetObject" value="#{@systemProperties}" /> 
     <property name="targetMethod" value="putAll" /> 
     <property name="arguments"> 
    <util:properties location="classpath:**${environment}/**environment.properties" /> 
</property> 
</bean> 

否則我應該有application.properties在部署之前替換每個環境。我確信有比這更好的解決方案。