2013-08-23 173 views
4

我使用的是spring web mvc項目,並且我將所有彈簧相關文件放在WEB-INF\spring之下,其中包括ormlite.xmljdbc.properties如何在彈簧上下文配置文件中找到屬性文件

現在我想找到jdbc.properties文件中的ormlite.xmlLike this

<context:property-placeholder location="/WEB-INF/spring/jdbc.properties"/> 

但是當我運行的應用程序,它會告訴我說:

Could not load properties

這不可能找到屬性文件。

什麼問題?

回答

9

從春季論壇:

的問題是,/ WEB-INF是無法訪問的,因爲它是沒有根的路徑 ,當你在使用你必須使用相同的路徑你測試用例 (包括src/main/webapp部分,但會使您的應用程序 不能運行)。

我建議您將jdbc.properties移動到src/main/resources 目錄,並簡單地使用classpath:前綴來加載屬性。

代碼:

<context:property-placeholder location="classpath:jdbc.properties"/> 

上面的代碼假定它們是在類路徑的根(這是 其中它們時,他們在src/main/resources是)。

我希望這可以幫助別人。

0

相反的:

<context:property-placeholder location="/WEB-INF/spring/jdbc.properties"/> 

用途:

<bean id="propertyConfigurer" 
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
     p:location="/WEB-INF/spring/jdbc.properties"/> 

而且你的屬性將在Spring文件中提供,並且不要忘記添加命名空間:xmlns:p="http://www.springframework.org/schema/p"

+0

不起作用。看到這個:[http://i.imgur.com/QmpQv6K.png] – hguser

+0

您使用的是哪個版本的Spring? –

+0

我正在使用3.2.3.RELEASE – hguser

0

我想您錯過了指示Spring如何嘗試加載屬性的前綴。我認爲你的定義必須是:

<context:property-placeholder location="file:/WEB-INF/spring/jdbc.properties"/> 

注意添加文件:前綴。

+0

我試圖添加'file:'前綴,它不起作用。 – hguser

+0

你有沒有試過file:WEB-INF/spring/jdbc.properties?即錯過了開始的斜槓? –

+0

是的,我已經嘗試了他們兩個。 – hguser

1

我有同樣的問題 - 類路徑之外的屬性文件。

我的解決辦法:

首先定義一個屬性的bean:

<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
     <property name="location"> 
      <value>/WEB-INF/your.properties</value> 
     </property> 
    </bean> 

在屬性佔位符然後引用它:

<context:property-placeholder properties-ref="configProperties" /> 

完美的作品很適合我!