天天看點

Spring PropertyPlaceholderConfigure 載入配置檔案

在開始這篇部落格的主題之前,我們先來了解一下Spring配置檔案以及包括的相關内容。

Spring PropertyPlaceholderConfigure 載入配置檔案
Spring PropertyPlaceholderConfigure 載入配置檔案
Spring PropertyPlaceholderConfigure 載入配置檔案
Spring PropertyPlaceholderConfigure 載入配置檔案
Spring PropertyPlaceholderConfigure 載入配置檔案

圖檔來自:http://book.51cto.com/art/201004/193743.htm(表示感謝)

Spring同意我們通過外部屬性檔案來配置其容器上下文屬性值。

比如。對于資料源中完畢連接配接資料庫的部分。我們能夠通過屬性檔案裡的鍵值對完畢對屬性值的填充,類似${key}。其關系例如以下:

Spring PropertyPlaceholderConfigure 載入配置檔案

問題一. Spring怎麼載入單個屬性檔案?

方法一:通過申明PropertyPlaceholderConfigurer bean對象完畢配置檔案的載入。

<beanid="testProperties"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 
    <propertyname="location"value="classpath:test.properties"/>
 
</bean>      

當中test.properties屬性檔案内容例如以下:

dbc.driverClassName=net.sourceforge.jtds.jdbc.Driver
jdbc.url=jdbc\:jtds\:sqlserver\://localhost\:1433/test
jdbc.username=sa
jdbc.password=123456      

載入之後,再通過${key}完畢屬性值得填充,比如:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
       <property name="driverClassName" value="${jdbc.driverClassName}" />
       <property name="url" value="${jdbc.url}"/>
       <property name="username" value="${jdbc.username}"/>
       <property name="password" value="${jdbc.password}"/>
</bean>      

方法二:通過context:property-placeholder屬性完畢載入

詳細例如以下:

<context:property-placeholderlocation="classpath:test.properties" />      

問題二:上述載入方式時載入一個properties檔案,假設要載入多個檔案,該怎樣實作?

事實上非常easy,例如以下:

<propertyname="systemPropertiesModeName"value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreResourceNotFound" value="true" />
       <property name="locations">
           <list>
              <value>classpath:test1.properties</value>
              <value>classpath:test2.properties </value>
           </list>
       </property>      

當中。ignore-resource-not-found:假設屬性檔案找不到,是否忽略,預設false,即不忽略,找不到将抛出異常。

systemPropertiesModeName:訓示後面的配置檔案裡的值是否會覆寫前面的值,

SYSTEM_PROPERTIES_MODE_FALLBACK:在解析一個占位符的變量的時候。假設不能擷取到該變量的值。就會拿系統屬性來嘗試,

SYSTEM_PROPERTIES_MODE_OVERRIDE:在解析一個占位符的時候。會先用系統屬性來嘗試,然後才會用指定的屬性檔案,

SYSTEM_PROPERTIES_MODE_NEVER:從來都不會使用系統屬性來嘗試。

問題三:有些時候,我們不希望載入project檔案夾屬性檔案,而希望載入磁盤檔案,如(D:/config/test.properties)

使用file:///或file:完畢絕對路徑的載入

例如以下:

<propertyname="location"value="file:///D:/config/test.properties"/>