2015-04-21 85 views
1

我使用的是Spring版本4.0.6.RELEASE,並試圖從屬性文件中讀取spring,並使用其中一個已解析的屬性向另一個屬性文件提供位置。我spring.xml文件有以下幾點:春天解決的屬性文件的位置需要解決這些屬性

<bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="locations"> 
     <list> 
      <value>classpath:application.properties</value> 
      <value>classpath:version.properties</value> 
      <!- The below file contains the another file location --> 
      <value>file:${catalina.base}/conf/instance.properties</value> 
      <value>${another.file.location}</value> 

     </list> 
    </property> 
    <property name="ignoreResourceNotFound" value="true"/> 
</bean> 

instance.properties包含:

account.id=BlahBlahBlah 
another.file.location=file:/Users/beardman/.myapp/local.properties 

和/Users/beardman/.myapp/local.properties包含:

magic.number=3 
database.endpoint=blah 

我不斷收到以下警告:

WARN [main] o.s.b.f.c.PropertyPlaceholderConfigurer Could not load properties from ServletContext resource [/${another.file.location}]: Could not open ServletContext resource [/${another.file.location}] 

在調試我的代碼時,我可以看到account.id被正確注入,但我永遠無法獲取magic.number或database.endpoint來顯示。我怎樣才能讓spring使用instance.properties文件中已解析的屬性作爲another.file.location的值?

編輯:添加屬性文件內容

+1

它看起來就像你的路徑值未設置正確的方式或不存在 – CodeFox

+0

這是一個很好的點@CodeFox,但我有驗證了這些文件確實存在於它們的正確位置,我實際上從instance.properties文件中獲取了屬性,從我的local.properties文件中什麼都沒有。 – beardman

回答

0

默認情況下,Spring會使用系統屬性替換屬性佔位符。既然你也想使用在外部文件中定義的屬性,你需要創建一個PropertyPlaceholderConfigurer
這個標籤是簡寫,但是如果你需要更多的控制,你可以將PropertyPlaceholderConfigurer定義爲一個bean。您applicationProperties bean之前加入這個

<context:property-placeholder location="file:${catalina.base}/conf/instance.properties"/> 

注意的是,文件中的屬性將在默認模式覆蓋系統性能。您可以指定系統屬性中加入屬性systemPropertiesMode="override"property-placeholder元件首先檢查

+0

正確地讀取了instance.properties文件中的屬性,但我無法獲得spring來翻譯在instance.properties中定義的another.file.location屬性,並實際讀取another.file.location中的屬性。 – beardman

+0

感謝您回覆。我嘗試了上下文:屬性佔位符在多個不同的配置和'another.file.location'永遠不會解決。 – beardman

+0

@beardman PropertyPlaceholderConfigurer的警告不是針對您發佈的配置的部分,而是針對另一個嘗試將$ {another.file.location}作爲屬性佔位符加載的bean。您需要使用PropertyPlaceholderConfigurer加載instance.properties,然後才能在任何地方使用$ {another.file.location}。如果您還嘗試從$ {another.file.location}加載屬性以用作佔位符,則需要將其放在第二個PropertyPlaceholderConfigurer中,位於具有instance.properties之後的某個位置。 –