spring 讀取設定檔的方法

來源:互聯網
上載者:User
 <!-- JDBC參數配置 --> <bean  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />  <property name="ignoreResourceNotFound" value="true" />  <property name="ignoreUnresolvablePlaceholders" value="true" />  <property name="locations">   <list>    <!-- 單元測試配置 -->    <value>classpath:config/config.properties</value>    <value>classpath:config/ofcard.properties</value>    <!-- 自測配置 -->    <value>/WEB-INF/conf/config.properties</value>    <value>/WEB-INF/conf/ofcard.properties</value>    <!-- 生產環境 -->    <value>file:/apps/conf/config.properties</value>    <value>file:/apps/conf/ofcard.properties</value>   </list>  </property> </bean>

PropertyPlaceholderConfigurer 這個類是spring用來處理系統設定檔並且具有將spring設定檔中的以${properties}的形式替換成key為properties的value其中成員變數systemPropertiesModeName是用來指示後面的設定檔中的值是否會覆蓋前面的值預設情況下如果設定檔中有不能解析的預留位置則會拋出異常ignoreUnresolvablePlaceholders用來指示忽略此異常,ignoreResourceNotFound用來指示如果檔案找不到則忽略以上locations中一個檔案配置了3個地方是為了在單元測試和自測已經生產環境下使用這樣設定檔的放置的位置就會更靈活。
有人會問systemPropertiesModeName 這可以設定的幾個值分別代表什麼含義通過閱讀PropertyPlaceholderConfigurer中的setSystemPropertiesMode方法上面的注釋可以發現:
     * Set how to check system properties: as fallback, as override, or never.
     * For example, will resolve ${user.dir} to the "user.dir" system property.
     * <p>The default is "fallback": If not being able to resolve a placeholder
     * with the specified properties, a system property will be tried.
     * "override" will check for a system property first, before trying the
     * specified properties. "never" will not check system properties at all.
     * @see #SYSTEM_PROPERTIES_MODE_NEVER
     * @see #SYSTEM_PROPERTIES_MODE_FALLBACK
     * @see #SYSTEM_PROPERTIES_MODE_OVERRIDE
fallback模式:在解析一個預留位置的變數的時候,如果不能擷取到該變數的值,就會拿系統屬性來嘗試,
override模式:在解析一個預留位置的時候,會先用系統屬性來嘗試,然後才會用指定的屬性檔案,
never模式:從來都不會使用系統屬性來嘗試。
本人在系統屬性這個概念上糾結了很長時間,後來嘗試的用System.getProperties的方法列印出所有的jvm的系統屬性發現user.dir是jvm的一個內建系統屬性,到了這邊我才明白原來spring設定檔中時可以直接用${}的形式來使用jvm的系統屬性的,

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.