我正嘗試讀取基於系統環境變量的配置文件。我的環境變量是FOO_ENV
,值爲dev
,dev.properties
包含屬性bar.host
和bar.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
。
我認爲myServer上的'ignoreUnresolvablePlaceholders'屬性是複製/粘貼錯誤? –
其實,因爲我不確定它應該去哪裏(找不到任何明確的解釋),我已經用'propertyConfigurer'和曾經具有無法解析的屬性來試用它。 –