2014-02-11 37 views
1

我正嘗試讀取基於系統環境變量的配置文件。我的環境變量是FOO_ENV,值爲devdev.properties包含屬性bar.hostbar.port如何在Spring上下文文件中使用帶有屬性文件的環境變量

<context:property-placeholder /> 
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:${FOO_ENV}.properties"></property> 
    <property name="ignoreUnresolvablePlaceholders" value="true" /> 
</bean> 

<bean id="myServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer"> 
    <property name="ignoreUnresolvablePlaceholders" value="true" /> 
    <constructor-arg type="String" value="http://${my.host}:${my.port}/" /> 
</bean> 

當我在Tomcat中部署此,我得到以下錯誤:

11:48:39.324 [localhost-startStop-14] ERROR o.s.web.context.ContextLoader - Context initialization failed 
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'myServer' defined in ServletContext resource [/WEB-INF/my-context.xml]: 
    Could not resolve placeholder 'my.host' in string value [http://${my.host}:${my.port}] 
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209) ~[spring-beans-3.1.2.RELEASE.jar:3.1.2.RELEASE] 

通過上下文文件,dev更換$FOO_ENV,我已確定,屬性文件可以被正確讀取。通過將FOO_ENV更改爲其他名稱,我可以證明Spring正在讀取環境變量。

看來元素

<property name="ignoreUnresolvablePlaceholders" value="true" /> 

應該讓春忽略${my.host}不是一個環境變量,但儘管我已經在不同的地方嘗試過了,我仍然得到了同樣的錯誤,這表明找不到my.host

+0

我認爲myServer上的'ignoreUnresolvablePlaceholders'屬性是複製/粘貼錯誤? –

+0

其實,因爲我不確定它應該去哪裏(找不到任何明確的解釋),我已經用'propertyConfigurer'和曾經具有無法解析的屬性來試用它。 –

回答

3

實際上你在這裏定義了兩個PropertyPlaceHolderConfigurers。一個通過上下文命名空間,另一個通過顯式。 Spring可能會選擇通過上下文命名空間創建的。您既可以設置「忽略-無法解決的」上下文標記並刪除propertyConfigurer豆像這樣:

<context:property-placeholder ignore-unresolvable="true"/> 

或者,如果你需要更多的控制權PropertyPlaceHolderConfigurer走另一條路,並刪除了上述內容:財產佔位符標記。

+0

'ignore-unresolvable'爲我工作。有沒有我能在文檔中發現的方法? –

相關問題