2011-06-24 71 views
2

這是一個「簡單」問題,我正在尋找一個如何操作和/或您是否愚蠢的操作。我對這兩個都開放。使用Spring和Webapp屬性佔位符查找屬性

我建立一個war文件,並希望結構爲:

WEB-INF/ 
    properties/ 
    <my properties files> 
    classes/ 
    ... 
    spring/ 
    <my spring files> 

那是愚蠢的?我知道我可以通過屬性佔位符來訪問屬性文件,但是我不想將屬性嵌套在類部分中 - 這對我來說沒有意義。

所以春天文件看起來像這樣:

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

如果我想訪問他們的類區域。我以爲

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

會讓我只是把目錄下的WEB-INF直接...我錯了(PS我認爲我:))。

有什麼建議嗎?

回答

3

這應該工作

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

WEB-INF沒有的在web-app的根,所以你需要WEB-INF添加到路徑。

spring-context-3.1.xsd

<xsd:attribute name="location" type="xsd:string"> 
<xsd:annotation> 
<xsd:documentation> 
<![CDATA[ 
    The location of the properties file to resolve placeholders against, as a Spring 
    resource location: a URL, a "classpath:" pseudo URL, or a relative file path. 
    Multiple locations may be specified, separated by commas. If neither location nor properties-ref is 
    specified, placeholders will be resolved against system properties. 


    ]]> 
</xsd:documentation> 
</xsd:annotation> 
</xsd:attribute> 
+0

謝謝sooo much! – rybit

+0

不客氣。很高興看到它的幫助。 – Jeesmon

0

我不確定你想實現什麼。這裏我用注入從基本性能屬性的方法文件到一個bean:

在春天文件(XML bean定義),我將引用添加到我的屬性文件(myfile.properties):

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

然後我添加了對屬性的引用(db.url是我的數據庫連接的URL地址,我只保留了在屬性文件中引用的bean屬性)。

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
    destroy-method="close"> 
    <!-- results in a setDriverClassName(String) call --> 
    <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
    <property name="url"><value>${db.url}</value></property> 
    <property name="username"><value>${db.login}</value></property> 
    <property name="password"><value>${db.password}</value></property> 

</bean> 

默認情況下,如果屬性未在屬性文件中定義,Spring使用系統屬性(這種行爲是可以改變的)。

+0

我很好地訪問屬性 - 這是我想要的文件居住的地方。而不是在WEB-INF/classes/properties/*。屬性中,我寧願使用WEB-INF/properties/*。屬性 – rybit

2

由於Classloader的類路徑將是/ classes目錄和/ lib目錄中的所有jar,因此無法按照您希望的方式執行此操作。這是戰爭文件的標準配置。

戰爭和耳朵有特定的配置,你必須遵循的文件是有效的。如果你仔細想想,如果有不同的供應商提供Web容器,如果沒有標準格式,可能會部署相同的戰爭文件,這很難實現。有一個pretty informative page here

實現類似於你想要的東西,你可以簡單地有/班/屬性目錄和/班/春從classpath中適當地看看他們。(「類路徑:性能/ myfile.properties)

+0

我認爲彈簧文件的首選位置是在WEB-INF/spring /中。我不記得我在哪裏讀過 - 但是您將其設置在web.xml文件中。 – rybit

+0

我認爲在構建之前目錄是'spring',但是一旦生成了WAR,它就會以'classes'結尾,這樣它就會在類路徑上結束。這可能不是你的願望,但WAR結構已經標準化了;你不應該試圖自定義它。 –

+0

我將離開屬性文件然後:)。另外 - 彈簧文件不會複製到類文件夾中。看看petshop [link](https://src.springframework.org/svn/spring-samples/petclinic/trunk/)。它由Maven構建,它直接複製WEB-INF,然後將src/main/resources複製到WEB-INF/classes /中,並且這些屬性通常位於src/main/resources中 – rybit