[英]How to use environment variables with properties file in Spring context file
我試圖基於系統環境變量讀取配置文件。 我的環境變量是FOO_ENV
,其值為dev
, dev.properties
包含屬性bar.host
和bar.port
。
<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" />
應該允許Spring忽略${my.host}
不是環境變量,但是雖然我已經在各個地方嘗試過,但我仍然得到相同的錯誤,這表明my.host
。
實際上你在這里定義了兩個PropertyPlaceHolderConfigurers。 一個通過上下文命名空間和一個顯式。 Spring可能會選擇通過上下文命名空間創建的那個。 您可以在上下文標記上設置'ignore-unresolvable'並刪除propertyConfigurer bean,如下所示:
<context:property-placeholder ignore-unresolvable="true"/>
或者,如果您需要對PropertyPlaceHolderConfigurer進行更多控制,請轉到另一種方式並刪除context:property-placeholder標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.