SpringのPropertyPlaceholderConfigurerを使用してファイルを読み込む

11453 ワード

目次
  • 一.概要
  • 二.XML方式
  • 三.Java符号化方式
  • 一.概要
  • 大規模なプロジェクトでは、システムの構成情報を統一的に管理することがよくあります.一般的には、構成情報をcfg.propertiesのファイルに構成し、システムを初期化すると、cfg.properties構成ファイルのkey value(キー値ペア)を自動的に読み取り、システムをカスタマイズして初期化します.
  • では、一般的にはjava.util.Properties、つまりjavaが持参したものを使用します.往々にして1つの問題は、ロードするたびに、私たちはこのプロファイルを手動で読む必要があります.1つは符号化が面倒で、2つはコードが優雅ではありません.往々にして私たちも自分でクラスを作成して、専門的に読み取り、これらの構成情報を保存します.
  • Webプロジェクトでは、相対パスでプロファイルのパスを得ることができますが、実行可能プロジェクトでは、チーム開発ではそれぞれの環境に応じてpropertiesプロファイルのパスを指定する必要があります.この場合、プロファイルのパスをjava仮想マシンJVMのカスタム変数(ランタイムパラメータ)に配置できます.たとえば、-Ddev.config=/dev.propertiesが探しているのは、ネイティブルートの下
  • Springには、BeanFactoryPostProcessorのサブクラスであるP r e r t y PlaceholderConfigurerが提供されています.その主な原理は.Springコンテナが初期化されるとxmlまたはannotationを読み込んでBeanを初期化します.初期化の際、このP r o p e r t y PlaceholderConfigurerはBeanの初期化をブロックし、初期化の際には構成の${pname}を置換し、私たちのPropertiesで構成したものに従って置換します.式を置換します.

  • 二.XML方式
    方式1
    
    
        
            
            
    
            
            
                
                    classpath:db.properties
                    classpath:db2.properties
                
            
        
    
    #db.properties 
    jdbc.driverClass==net.sourceforge.jtds.jdbc.Driver 
    jdbc.url=jdbc:mysql://localhost:3306/test?  
    jdbc.username=anqi 
    jdbc.password=123456 
    #db2.properties 
    name=anqi 
    age=23 
    import org.junit.Test; import org.junit.runner.RunWith; 
    import org.springframework.beans.factory.annotation.Value; 
    import org.springframework.test.context.ContextConfiguration; 
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
    
    @RunWith(SpringJUnit4ClassRunner.class) 
    @ContextConfiguration("classpath:spring-context.xml") 
    public class TestPropertyPlaceHoder2 {     
      @Value("${jdbc.username}")     
      private String username;     
      @Value("${jdbc.password}")     
      private String password;     
      @Value("${name}")     
      private String name;     
      @Value("${age}")     
      private int age;      
      
      @Test     
      public void testResource() {         
        System.out.println("username: " + username);         
        System.out.println("password: " + password);         
        System.out.println("name: " + name);         
        System.out.println("age: " + age);     
      } 
    } 
    /* username: anqi     password: 123456     name: anqi     age: 23 */ 

    方式2
     
      
    
     

    注意:PropertyPlaceholderConfigurerを使用してもcontext:property-placeholderを使用しても、Springフレームワークはプロファイルのキー値ペアだけでなく、Jvmが初期化したシステムの情報も読み取ることを覚えておく必要があります.場合によっては、構成キーに名前付きルールを設定する必要があります.たとえば、
     jdbc.username   
     jdbc.password  

    また、次のような構成方法で構成することもできます.ここで、NEVERはシステム構成情報を読み込まないことを意味します.
      
    
    SYSTEM_PROPERTIES_MODE_FALLBACK:              。            。          ,      
    SYSTEM_PROPERTIES_MODE_OVERRIDE:           。          ,            ,      
    SYSTEM_PROPERTIES_MODE_NEVER:              。    

    三.Java符号化方式
    符号化の方式を採用するのは明らかにもっと柔軟で、私達が1つのプロジェクトをする時、オンラインでローカルで走るのとサーバーのオンラインで走る時、必要なパラメータはきっと多くの違いがあって、私達はxml java符号化の方式を通じてどの配置の方案を採用することを指定することができて、同じ配置の方案の中でオンラインの配置のファイルの住所を前に置くことができて、オンラインプロファイルがない場合は、ローカル構成でプロジェクトを実行します.
    spring-context.xml
    
        
        
              
            
                
                    
                    
                    
                    classpath:db.properties
                    classpath:db2.properties
                
            
            
            
                
                    classpath:db3.properties
                
            
        
    

    db.properties
    jdbc.driverClass==net.sourceforge.jtds.jdbc.Driver 
    jdbc.url=jdbc:mysql://localhost:3306/test?  
    jdbc.username=anqi jdbc.
    password=123456 
    pro=1 
    version=db1 

    db2.properties
    name=anqi 
    age=23 
    pro=2 
    version=db2 

    db3.properties
    pro=3 

    dev.properties
    company=abc version=dev.config 

    構成されたツールクラスの読み込み
    import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.core.io.Resource;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.*;
    
    public class PropertiesUtil extends PropertyPlaceholderConfigurer {
    
        private static Resource electResource;
    
        private static Properties configProperties = new Properties();
        private static Properties programProperties = new Properties();
    
        public PropertiesUtil() {}
    
            /**
          *    spring-context         ,         properties         
          *          db2.properties        db1.properties      key
          * @param locations
            */
          public void setLocations(Resource... locations) {
                    List existResourceList = new ArrayList<>();
    
                    Resource devConfig = getDevConfig();
              if (devConfig != null) {
                  existResourceList.add(devConfig);
              }
    
              Resource resource;
              for(int i = 0; i < locations.length; ++i) {
                  resource = locations[i];
                  if (resource.exists()) {
                      existResourceList.add(resource);
                      //dev db.properties db2.properties 
                  }
              }
    
            Collections.reverse(existResourceList);
            //db2.properties db.properties dev
    
            if (!existResourceList.isEmpty()) {
                electResource = existResourceList.get(existResourceList.size() - 1);
                //dev
            }
    
            try {
                configProperties.load(electResource.getURL().openStream());
                if (existResourceList != null && existResourceList.size() > 1) {
                for(int i = existResourceList.size() - 2; i >= 0; --i) {
                    Properties backupConfig = new Properties();
                    //       db1 db2
                  backupConfig.load(((Resource)existResourceList.get(i)).getURL().openStream());
    
                  Iterator iterator = backupConfig.keySet().iterator();
    
                  //         db3.properties、db4.peoperties      db.properties
                  //      key         key
                  while(iterator.hasNext()) {
                      Object key = iterator.next();
                      if (!configProperties.containsKey(key)) {
                          configProperties.put(key, backupConfig.get(key));
                      }
                  }
                }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
            /**
            *   programConfig          programeConfig  
            * (   db3.properties     programeConfig)
            *        (          )    key     value
            * @param locations
            */
          public void setProgramConfig (Resource... locations){
    
              List existResourceList = new ArrayList<>();
    
              Resource resource;
              for(int i = 0; i < locations.length; ++i) {
                  resource = locations[i];
                  if (resource.exists()) {
                      existResourceList.add(resource);
                  }
              }
    
            if (!existResourceList.isEmpty()) {
                try {
                    Iterator iterator = existResourceList.iterator();
                    while (iterator.hasNext()) {
                        resource = iterator.next();
                        programProperties.load(resource.getURL().openStream());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            Resource devConfig = getDevConfig();
            if (devConfig != null) {
                try {
                    Properties devProperties = new Properties();
                    devProperties.load(devConfig.getURL().openStream());
                    Iterator iterator = devProperties.keySet().iterator();
    
                    while(iterator.hasNext()) {
                        Object key = iterator.next();
                        programProperties.put(String.valueOf(key), 
                                devProperties.getProperty(String.valueOf(key), ""));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
                *            (                )
                * @return
            */
          private static Resource getDevConfig() {
              String s = System.getProperty("dev.config", "");
              File devConfig = new File(s);
              return !s.trim().equals("") && devConfig.exists() && devConfig.isFile() ? 
                          new FileSystemResource(s) : null;
          }
    
        /**
          *      properties          key
          * @param key
          * @return
                */
          public static String get(String key){
                    return programProperties.containsKey(key) ? 
                  programProperties.getProperty(key) : configProperties.getProperty(key);
          }
    
            public static void show() {
            System.out.println("db_1 keys: "+configProperties.keySet());
            System.out.println("db_2 keys: "+programProperties.keySet());
        }
    }
    
    

    テストクラス
    package com.anqi.testPropertyPlaceHoder;  
    import org.springframework.context.ApplicationContext; 
    import org.springframework.context.support.ClassPathXmlApplicationContext;   
    public class TestPropertyPlaceHoder  {      
        public static void main(String[] args) {         
            ApplicationContext al = new ClassPathXmlApplicationContext("classpath:spring-context.xml");         
            PropertiesUtil.show();         
            System.out.println(PropertiesUtil.get("version")); 
    
            //-Ddev.config=/dev.properties        
            System.out.println(PropertiesUtil.get("company"));
            System.out.println(PropertiesUtil.get("pro"));
            //db_1 keys: [name, jdbc.password, version, company, jdbc.url, pro, jdbc.driverClass, jdbc.username, age] 
            //db_2 keys: [company, version, pro] 
            //dev.config 
            //abc 
            //3     
        } 
    }