spring 集成的項目,Properties配置文件外移


  本人一直沒有寫博客的習慣,這應該是我第一發布與技術相關的博客,技術方面有闡述不到位的地方,請多多指教,在下感激成分!

前言

  前段時間做了一個項目,在開發的過程中,也沒有考慮到配置文件的問題。后來項目完成了,打包的時候要求,要求將項目中的配置文件外移,方便修改配置文件。花了我兩天多的時間才弄明白,於是記錄下,以防以后再遇到類似問題。

配置文件位於classpath下

  使用spring的org.springframework.beans.factory.config.PropertyPlaceholderConfigurer類加載Properties配置文件,通過源碼可以知道,默認加載的是classpath下的文件,配置如下:

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

 

如果有多個配置文件加載,則:

<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
   <list>
  <value>classpath:config/init.properties</value>    <value>classpath:config/init.properties</value> </list> </property> </bean>

 

這樣spring就能夠加載properties文件了。

配置文件位於外部目錄

  但是對於外部目錄的配置文件,使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer也是可以加載的,不過要修改他的路徑配置方式,如下:

<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
   <list>
     <value>file:${user.dir}/config/init.properties</value>
     <value>file:${user.dir}/config/init2.properties</value>
   </list>
  </property>
 </bean>

 

這樣就可以成功加載外部目錄的配置文件了,${user.dir}是系統變量,指用戶當前目錄所在。

代碼中加載配置文件

  應該某些需求,配置文件得從java代碼是加載,這里我就說一樣代碼中加載外部目錄的配置文件的方式,加載classpath目錄下的配置文件這里就不再多說了,相

信網上有太多較好的簡答。如下代碼:

private static final Properties sysConfig = new Properties();

    static {
        try {
            InputStream iStream = new FileInputStream(new File("config", "shellConfig.properties"));
            sysConfig.load(iStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static String getPropertyValue(String key){
        return sysConfig.getProperty(key);
    }

 希望對大家有所幫助!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM