2011-09-19 33 views
1

我在Tomcat中使用PropertyPlaceholderConfigurer & ContextLoaderListener。PropertyPlaceholderConfigurer with Tomcat&ContextLoaderListener

這工作(與屬性的文件的名稱硬編碼):

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

但是,這(與屬性的文件的名稱與$替換{ENV}):

<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:properties/${env}.properties"/> 
</bean> 

[ Thread-2] 15:50:16 ERROR ContextLoader - 上下文初始化失敗 org.springframework.beans.factory.BeanInitializationException:無法加載屬性;嵌套的異常是java.io.FileNotFoundException:類路徑資源[屬性/ $ {env} .properties]無法打開,因爲它不存在

我知道該文件存在,因爲它在我硬編碼時起作用。

我試過在啓動Tomcat和設置環境變量時使用-Denv = test。我使用我自己的主方法而不是ContextLoaderListener在Tomcat外部工作。

我會做什麼錯?使用context.xml或web.xml中的條目而不是-Denv = test可以實現同樣的功能嗎?

感謝

PS我也試過:

<bean id="initialcorePropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="systemPropertiesModeName"> 
     <value>SYSTEM_PROPERTIES_MODE_OVERRIDE</value> 
    </property> 
    <property name="searchSystemEnvironment"> 
     <value type="boolean">true</value> 
    </property> 
    <property name="ignoreUnresolvablePlaceholders" value="true" /> 
</bean> 

<bean id="corePropertyConfigurer" depends-on="initialcorePropertyConfigurer" lazy-init="true" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:properties/${env}.properties" /> 
</bean> 

,但我得到了同樣的錯誤。

回答

2

你不能在你的PropertyPlaceholderConfigurer定義使用屬性佔位符。雞和先有蛋。

你可以使用,無論#{ systemProperties['env'] }

或者你可以繼承PropertyPlaceholderConfigurer並覆蓋setLocation()處理的佔位符。

+0

我的PropertyPlaceholderConfigurer定義中有一個屬性佔位符工作得很好。但只能用我自己的主要方法,不要使用Tomcat和ContextLoaderListener。 另外,即使我在我的電子郵件末尾使用了2個PropertyPlaceholderConfigurer,它仍會給出同樣的問題。 – Carl

+0

謝謝。根據您的建議,我將$ {env}更改爲#{systemProperties ['env']},並解決了錯誤。我仍然不清楚它爲什麼可以與我自己的主要工作,但不在Tomcat和ContextLoaderListener中。 – Carl

0

組完整的位置像-DpropFileLocation=classpath:env1.properties-DpropFileLocation=classpath:env2.properties而不只是它的一部分:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="ignoreResourceNotFound" value="true"/> 
    <property name="location" value="${propFileLocation}"/> 
</bean> 
+0

畢竟它有一個黑客有更乾淨的方法來做到這一點。 – Santosh

+0

感謝您的建議,但我得到同樣的錯誤。 – Carl

0

您需要將環境變量CATALINA_OPTS或JAVA_OPTS設置爲-Denv = test。最好的辦法是創建一個setenv.bat(如果你在unix上,則爲.sh),並在其中添加這個環境變量定義。

如果您將它作爲參數傳遞給startup.bat(.sh),它將不會生效,我假設您正在做什麼。

+0

謝謝。我剛剛嘗試過,似乎沒有什麼區別。我已經添加了一個簡單的servlet, – Carl

+0

謝謝。我剛剛嘗試過,似乎沒有什麼區別。我已經添加了一個執行簡單System.getProperties()的servlet,然後將它們打印出來。我在該列表中看到屬性env。所以它在我的Tomcat代碼中可用。 – Carl

0

在此論壇上有一個similar question需要將屬性文件進行外部化。退房this solution。它認爲你的問題是相似的,而不是通過env作爲系統變量,將它設置爲env變量。

+0

謝謝。我已經嘗試使用env變量並得到相同的錯誤。 – Carl

相關問題