最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring如何使用PropertyPlaceholderConfigurer讀取文件

 更新時(shí)間:2019年12月10日 09:19:11   作者:海向  
這篇文章主要介紹了Spring如何使用PropertyPlaceholderConfigurer讀取文件,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了Spring如何使用PropertyPlaceholderConfigurer讀取文件,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

一. 簡(jiǎn)介

大型項(xiàng)目中,我們往往會(huì)對(duì)我們的系統(tǒng)的配置信息進(jìn)行統(tǒng)一管理,一般做法是將配置信息配置與一個(gè)cfg.properties 的文件中,然后在我們系統(tǒng)初始化的時(shí)候,系統(tǒng)自動(dòng)讀取 cfg.properties 配置文件中的 key value(鍵值對(duì)),然后對(duì)我們系統(tǒng)進(jìn)行定制的初始化。

那么一般情況下,我們使用 的 java.util.Properties, 也就是 java 自帶的。往往有一個(gè)問題是,每一次加載的時(shí)候,我們都需要手工的去讀取這個(gè)配置文件,一來(lái)編碼麻煩,二來(lái)代碼不優(yōu)雅,往往我們也會(huì)自己創(chuàng)建一個(gè)類來(lái)專門讀取,并儲(chǔ)存這些配置信息。

對(duì)于 web 項(xiàng)目來(lái)說,可以通過相對(duì)路徑得到配置文件的路徑,而對(duì)于可執(zhí)行項(xiàng)目,在團(tuán)隊(duì)開發(fā)中就需要根據(jù)各自的環(huán)境來(lái)指定 properties 配置文件的路徑了。對(duì)于這種情況可以將配置文件的路徑放在 java 虛擬機(jī) JVM 的自定義變量(運(yùn)行時(shí)參數(shù))中,例如:-Ddev.config=/dev.properties 尋找的是本機(jī)根目錄下

Spring中提供著一個(gè) PropertyPlaceholderConfigurer,這個(gè)類是 BeanFactoryPostProcessor 的子類。其主要的原理在是。Spring容器初始化的時(shí)候,會(huì)讀取 xml 或者 annotation 對(duì) Bean 進(jìn)行初始化。初始化的時(shí)候,這個(gè) PropertyPlaceholderConfigurer 會(huì)攔截 Bean 的初始化,初始化的時(shí)候會(huì)對(duì)配置的 ${pname} 進(jìn)行替換,根據(jù)我們 Properties 中配置的進(jìn)行替換。從而實(shí)現(xiàn)表達(dá)式的替換操作 。

二. XML 方式

方式1

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <!-- 對(duì)于讀取一個(gè)配置文件采取的方案 -->
    <!--<property name="location" value="classpath:db.properties"/>-->

    <!--對(duì)于讀取多個(gè)配置文件采取的方案-->
    <property name="locations">
      <list>
        <value>classpath:db.properties</value>
        <value>classpath:db2.properties</value>
      </list>
    </property>
  </bean>
</beans>
#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

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"      
  <context:property-placeholder location="classpath:db.properties,classpath:db2.properties"/> 

</beans> 

注意:我們知道不論是使用 PropertyPlaceholderConfigurer 還是通過 context:property-placeholder 這種方式進(jìn)行實(shí)現(xiàn),都需要記住,Spring框架不僅僅會(huì)讀取我們的配置文件中的鍵值對(duì),而且還會(huì)讀取 Jvm 初始化的一下系統(tǒng)的信息。有時(shí)候,我們需要將配置 Key 定一套命名規(guī)則 ,例如

jdbc.username

jdbc.password

同時(shí),我們也可以使用下面這種配置方式進(jìn)行配置,這里我配 NEVER 的意思是不讀取系統(tǒng)配置信息。

<context:property-placeholder location="classpath:db.properties,classpath:db2.properties"   
     system-properties-mode="NEVER"/>
  • SYSTEM_PROPERTIES_MODE_FALLBACK:在解析一個(gè)占位符的變量的時(shí)候。假設(shè)不能獲取到該變量的值。就會(huì)拿系統(tǒng)屬性來(lái)嘗試,
  • SYSTEM_PROPERTIES_MODE_OVERRIDE:在解析一個(gè)占位符的時(shí)候。會(huì)先用系統(tǒng)屬性來(lái)嘗試,然后才會(huì)用指定的屬性文件,
  • SYSTEM_PROPERTIES_MODE_NEVER:從來(lái)都不會(huì)使用系統(tǒng)屬性來(lái)嘗試。

三. Java 編碼方式

采取編碼的方式顯然更加靈活,當(dāng)我們?cè)谧鲆粋€(gè)項(xiàng)目時(shí),在線下本地跑和在服務(wù)器線上跑時(shí),需要的參數(shù)肯定有諸多不同,我們可以通過 xml java 編碼的方式來(lái)指定采用哪一個(gè)配置方案,同一個(gè)配置方案中也可以將線上配置文件的地址放在前面,沒有線上配置文件就采用本地配置的方式來(lái)運(yùn)行項(xiàng)目。

spring-context.xml

<bean>
  <!-- 配置 preoperties文件的加載類 -->
  <bean class="com.anqi.testPropertyPlaceHoder.PropertiesUtil">
    <!-- 配置方案1 優(yōu)先級(jí)更高 配置方案1找不到 key 才會(huì)去配置方案 2 里面找--> 
    <property name="locations">
      <list>
        <!-- 這里支持多種尋址方式:classpath 和 file -->
        <!-- 推薦使用file的方式引入,這樣可以將配置和代碼分離 -->
        <!--<value>file:/conf/localpro.properties</value>-->
        <value>classpath:db.properties</value>
        <value>classpath:db2.properties</value>
      </list>
    </property>
    <!-- 配置方案2 -->
    <property name="programConfig">
      <list>
        <value>classpath:db3.properties</value>
      </list>
    </property>
  </bean>
</beans>

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() {}

    /**
   * 根據(jù) spring-context 配置文件中的配置,來(lái)將項(xiàng)目下對(duì)應(yīng)的 properties 文件加載到系統(tǒng)中
   * 并且經(jīng)過特殊處理 db2.properties 不允許覆蓋掉 db1.properties 中相同的 key
   * @param locations
    */
   public void setLocations(Resource... locations) {
        List<Resource> 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 進(jìn)行更新 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)
    * 包含運(yùn)行時(shí)方案(運(yùn)行時(shí)配置優(yōu)先級(jí)最高)會(huì)覆蓋 key 相同的 value
    * @param locations
    */
   public void setProgramConfig (Resource... locations){

     List<Resource> 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<Resource> 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();
      }
    }
  }

  /**
      * 在運(yùn)行期間傳入配置參數(shù)(可以將配置文件放在本機(jī)或服務(wù)器上)
      * @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 配置文件中的某個(gè) 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());
  }
}

測(cè)試類

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 傳入運(yùn)行時(shí)參數(shù)
    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   
  } 
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Mybatis-plus 查詢條件為空不生效問題及解決

    Mybatis-plus 查詢條件為空不生效問題及解決

    這篇文章主要介紹了Mybatis-plus 查詢條件為空不生效問題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 利用微信小程序+JAVA實(shí)現(xiàn)微信支付的全過程

    利用微信小程序+JAVA實(shí)現(xiàn)微信支付的全過程

    微信支付是一種在線支付解決方案,允許用戶通過微信內(nèi)的支付功能進(jìn)行付款,下面這篇文章主要給大家介紹了關(guān)于利用微信小程序+JAVA實(shí)現(xiàn)微信支付的相關(guān)資料,需要的朋友可以參考下
    2024-08-08
  • Java修改圖片大小尺寸的簡(jiǎn)單實(shí)現(xiàn)

    Java修改圖片大小尺寸的簡(jiǎn)單實(shí)現(xiàn)

    這篇文章主要介紹了Java修改圖片大小尺寸的簡(jiǎn)單實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 解決Java執(zhí)行Cmd命令出現(xiàn)的死鎖問題

    解決Java執(zhí)行Cmd命令出現(xiàn)的死鎖問題

    這篇文章主要介紹了關(guān)于Java執(zhí)行Cmd命令出現(xiàn)的死鎖問題解決,解決方法就是在waitfor()方法之前讀出窗口的標(biāo)準(zhǔn)輸出、輸出、錯(cuò)誤緩沖區(qū)中的內(nèi)容,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • Spring如何解決單例bean線程不安全的問題

    Spring如何解決單例bean線程不安全的問題

    這篇文章主要介紹了Spring如何解決單例bean線程不安全的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2020-12-12
  • Java 高并發(fā)七:并發(fā)設(shè)計(jì)模型詳解

    Java 高并發(fā)七:并發(fā)設(shè)計(jì)模型詳解

    本文主要介紹Java高并發(fā) 并發(fā)設(shè)計(jì)模型的知識(shí),這里主要講解 1. 什么是設(shè)計(jì)模式 2. 單例模式 3. 不變模式 4. Future模式 5. 生產(chǎn)者消費(fèi)者,有需要的小伙伴可以參考下
    2016-09-09
  • RestTemplate發(fā)送form-data請(qǐng)求上傳rul資源文件及對(duì)象參數(shù)方式

    RestTemplate發(fā)送form-data請(qǐng)求上傳rul資源文件及對(duì)象參數(shù)方式

    這篇文章主要介紹了RestTemplate發(fā)送form-data請(qǐng)求上傳rul資源文件及對(duì)象參數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • SpringBoot Maven打包失敗報(bào):class lombok.javac.apt.LombokProcessor錯(cuò)誤的解決辦法

    SpringBoot Maven打包失敗報(bào):class lombok.javac.apt.Lombo

    最新項(xiàng)目部署的時(shí)候,出現(xiàn)了一個(gè)maven打包失敗的問題,報(bào):class lombok.javac.apt.LombokProcessor錯(cuò)誤,所以本文給大家介紹了如何解決SpringBoot Maven 打包失敗:class lombok.javac.apt.LombokProcessor 錯(cuò)誤,需要的朋友可以參考下
    2023-12-12
  • 淺談Servlet開發(fā)技術(shù)基礎(chǔ)

    淺談Servlet開發(fā)技術(shù)基礎(chǔ)

    這篇文章主要介紹了淺談Servlet開發(fā)技術(shù)基礎(chǔ),具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • Win10 IDEA遠(yuǎn)程連接HBase教程

    Win10 IDEA遠(yuǎn)程連接HBase教程

    在Windows 10上,通過IDEA連接到虛擬機(jī)中的Hadoop和HBase需要關(guān)閉虛擬機(jī)防火墻,并修改相關(guān)配置文件中的IP地址,此外,創(chuàng)建Maven項(xiàng)目并添加依賴是必要步驟,最后,通過Java代碼和HBase Shell命令進(jìn)行操作,此過程涉及的技術(shù)包括虛擬機(jī)配置、防火墻管理、文件編輯和項(xiàng)目管理等
    2024-11-11

最新評(píng)論

威海市| 乡城县| 怀安县| 六枝特区| 中超| 兰坪| 霍林郭勒市| 茌平县| 平罗县| 隆回县| 昌江| 鄂托克前旗| 五指山市| 桐乡市| 定陶县| 麟游县| 定西市| 额敏县| 大同县| 兴城市| 呼伦贝尔市| 灌南县| 富蕴县| 杭州市| 旬邑县| 剑川县| 巴南区| 荥阳市| 平乡县| 黄骅市| 陆丰市| 穆棱市| 江达县| 桦南县| 鲜城| 巴楚县| 宜黄县| 明星| 开封县| 汉源县| 敦化市|