亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用Java編寫一個好用的解析配置工具類

 更新時間:2024年11月03日 10:06:57   作者:jooLs薯薯熹  
這篇文章主要為大家詳細介紹了如何使用Java編寫一個好用的解析配置工具類,支持解析格式有properties,yaml和yml,感興趣的可以了解下

需求一: 加載解析 .properties 文件

對于一個 .properties 配置文件,如何用 Java 加載讀取并解析其中的配置項呢?

方式一: 直接使用 JDK 自帶的 Properties

Map 接口實現(xiàn)類 —— Properties

基本介紹 & 常用方法

  • Properties 類繼承自 Hashtable 類并且實現(xiàn)了 Map 接口,也是使用一種鍵值對的形式來保存形式
  • 使用特點和 Hashtable 類似
  • 用于存儲 xxx.properties 文件中,加載數(shù)據(jù)到 Properties 類對象進行讀取和修改
  • xxx.properties 通常被作為配置文件
  • 通過 k-v 形式存放數(shù)據(jù),但是 keyvalue 不能為 null

Properties類常用方法

public class PropertiesAPIs {

    public static void main(String[] args) {

        Properties properties = new Properties();

        //增加
//        properties.put(null, "abc");    報錯NullPointerException
//        properties.put("a", null);      報錯NullPointerException

        properties.put("john", 100);
        properties.put("wakoo", 100);
        properties.put("john", 11);     //相同的 key 會覆蓋

        System.out.println("properties =" + properties);

        System.out.println(properties.get("john"));     //11
        System.out.println(properties.get("wakoo"));    //100
    }
}

解析 Properties 配置文件 - 基于 load 方法

  • load: 加載配置文件鍵值對到 Properties 對象
  • list: 將數(shù)據(jù)顯示到指定設備
  • getProperty(key): 根據(jù)鍵獲取值
  • setProperty(key,value): 設置鍵值對到 Properties 對象
  • store 將 Properties 中的鍵值對存儲到配置文件,IDEA 中如果保存的信息含有中文,會自動存儲為 Unicode

示例

a. 創(chuàng)建一份 mysql.properties

ip=localhost
user=root
password=123456
datasource=druid

b. 解析 .properties 常用方法

public class PropertiesLoadUtils {

    public static void main(String[] args) throws IOException {

        Properties properties = new Properties();

        //load()可傳入 Reader 或者 InputStream
        properties.load(PropertiesLoadUtils.class.getResourceAsStream("/mysql.properties"));
//        properties.load(new FileReader("src/main/resources/mysql.properties"));

        //將所有 k-v 顯示
        properties.list(System.out);
        System.out.println("----");
        System.out.println(properties.get("user"));     //root
        System.out.println(properties.get("password")); //123456
        System.out.println(properties.get("ip"));       //localhost
        System.out.println(properties.get("datasource"));   //druid

        //設置屬性
        properties.setProperty("user", "Wakoo");
        System.out.println(properties.get("user")); //Wakoo

        //設置中文并且寫入到 .properties 文件
        properties.setProperty("user", "加瓦編程");
    
        //中文默認會以 Unicode 編碼寫入
        properties.store(new FileOutputStream("src/main/resources/mysql.properties"),"寫入中文");

        
        //重新讀取,查看是否正確編碼中文
        properties.load(new FileReader("src/main/resources/mysql.properties"));
        System.out.println(properties.getProperty("user"));
    }
}

輸出結果

方式二: 基于 Hutools - Props 包裝工具類

參考文檔

Hutool - Props 擴展類介紹

Hutool - Props - JavaDoc

Properties做了簡單的封裝,提供了方便的構造方法

常用方法

  • Props(): 構造
  • getProp(Resource resource): 靜態(tài)方法,獲取 Classpath 下的 Proeprties 文件
  • getProp(Resource resource, Charset charset): 靜態(tài)方法,作用同上,可指定編碼
  • load(Resource resource): 初始化配置文件
  • getStr(String key): 獲取字符串型屬性值
  • getStr(String key, String defaultValue): 獲取字符串型屬性值,若獲得的值為不可見字符使用默認值
  • setProperty(String key, Object value): 設置值,無給定鍵則創(chuàng)建。設置周未持久化
  • store(String absolutePath): 持久化當前設置,覆蓋方式
  • propertyNames(): 繼承自 Properties 獲取所有配置名稱
  • entrySet(): 繼承自 HashTable得到 Entry集,用于遍歷

示例

導入依賴

<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>${yours.version}</version>
</dependency>

基本使用

Props props = new Props("test.properties");
String user = props.getProperty("user");
String driver = props.getStr("driver");

測試

public class HutoolProps {
    public static void main(String[] args) throws IOException {

        //加載方式一: 基于 InputStream
//        InputStream in = HutoolProps.class.getResourceAsStream("/mysql.properties");
//        Props props = new Props();

        //加載方式二: 基于絕對路徑字符串, 支持定義編碼
        Props props = new Props("mysql.properties", StandardCharsets.UTF_8);

        //加載方式三: 傳入 Properties 對象
//        Properties properties = new Properties();
//        properties.load(new FileReader("src/main/resources/mysql.properties"));
//        Props props = new Props(properties);

        //還有其他方式....

        //獲取單個配置項
        
        System.out.println("user屬性值:" + props.getStr("user"));  //root
        System.out.println("user屬性值:" + props.getStr("adim", "ROOT"));  //ROOT
        
        //所有屬性鍵值
        Enumeration<?> enumeration = props.propertyNames();
        System.out.println("屬性有如下:");
        while (enumeration.hasMoreElements()) {
            System.out.println(enumeration.nextElement());
        }

        Set<Map.Entry<Object, Object>> entries = props.entrySet();
        System.out.println("---- 遍歷所有配置項 ----");
        for (Map.Entry<Object, Object> entry : entries) {
            System.out.println("key:" + entry.getKey() + " -> value:" + entry.getValue());
        }
        System.out.println("--------");

        //設置值,無給定鍵創(chuàng)建之。設置后未持久化
        props.setProperty("ip", "127.0.0.1");

        //若為 true, 配置文件更變時自動修改
        /*
         啟動一個 SimpleWatcher 線程監(jiān)控
            this.watchMonitor = WatchUtil.createModify(this.resource.getUrl(), new SimpleWatcher() {
                public void onModify(WatchEvent<?> event, Path currentPath) {
                    Props.this.load();
                }
            });
            this.watchMonitor.start();
         */
        props.autoLoad(true);
    }
}

輸出結果

需求二: 加載解析 .yaml/.yml 文件

支持讀取 application.yml、application.yaml 等不同格式的配置文件。

方法: 基于 SnakeYAML 工具

參考文檔

SnakeYAML - 倉庫

SnakeYaml - Java - Doc

快速入門教程

常用方法

  • Yaml(): 構造器
  • Yaml(BaseConstructor constructor): 構造器,自動檢測對象類型,借助 load() 可反序列化為相關類型對象
  • load(InputStream io): 基于 InputStream 加載單個 YAML 文件
  • load(Reader io): 基于 Reader 加載單個 YAML 文件
  • load(String yaml): 基于路徑字符串加載單個 YAML

示例

a. 導入依賴

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>${yours.version}</version>            
</dependency>

b. 創(chuàng)建 application.yml 文件

user: root
password: 123456
datasource: druid
ip: 127.0.0.1

測試 - 基于 InputStream 加載**

public class YamlUtils {

    public static void main(String[] args) {

        //基于 SankeYaml 工具類完成轉換
        Yaml yaml = new Yaml();

        //基于 InputStream
        InputStream inputStream = YamlUtils.class
        .getClassLoader().getResourceAsStream("application.yml");

        //可直接封裝成 Map
        /*
         * Parse the only YAML document in a stream and produce the corresponding Java object.
         *
         * @param io data to load from (BOM is respected to detect encoding and removed from the data)
         * @param <T> the class of the instance to be created
         * @return parsed object

        @SuppressWarnings("unchecked")
        public <T> T load(InputStream io) {
            return (T) loadFromReader(new StreamReader(new UnicodeReader(io)), Object.class);
        }
         */
        Map<String, Object> map = yaml.load(inputStream);

        for (String s : map.keySet()) {
            System.out.println("key:" + s + " -> value:" + map.get(s));
        }
    }
}

輸出結果

測試 - 基于 Reader 加載并直接封裝返回目標類型

a. 創(chuàng)建目標類型 DbConfigapplication.yml內配置一一對應

import lombok.Data;

/**
 * @description:
 * user: root
 * password: 123456
 * datasource: druid
 * ip: 127.0.0.1
 */
@Data
public class DbConfig {

    private String user;
    private String password;
    private String datasource;
    private String ip;
}

b.測試類

import org.junit.Test;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

@Test
public void testNestObj() {

    //Constructor 為 snakeyaml 依賴包內 class
    Yaml yaml = new Yaml(new Constructor(DbConfig.class, new LoaderOptions()));

    DbConfig dbConfig = null;

    //基于 FileReader
    try (FileReader reader = new FileReader("src/main/resources/application.yml")) {
        //加載 yaml 配置, 自動轉換為 DbConfig
        dbConfig = yaml.load(reader);
        System.out.println(dbConfig);

        //查詢 DbConfig 對象屬性
        System.out.println(dbConfig.getUser());
        System.out.println(dbConfig.getPassword());
        System.out.println(dbConfig.getIp());
        System.out.println(dbConfig.getDatasource());
    } catch (IOException e) {
        System.out.println(e.getMessage());
        throw new RuntimeException(e);
    }
}

輸出結果

到此這篇關于使用Java編寫一個好用的解析配置工具類的文章就介紹到這了,更多相關Java解析配置工具類內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Springboot @Configuration與自動配置詳解

    Springboot @Configuration與自動配置詳解

    這篇文章主要介紹了SpringBoot中的@Configuration自動配置,在進行項目編寫前,我們還需要知道一個東西,就是SpringBoot對我們的SpringMVC還做了哪些配置,包括如何擴展,如何定制,只有把這些都搞清楚了,我們在之后使用才會更加得心應手
    2022-07-07
  • Spring-IOC容器-Bean管理-基于XML方式超詳解

    Spring-IOC容器-Bean管理-基于XML方式超詳解

    這篇文章主要介紹了Spring為IOC容器Bean的管理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2021-08-08
  • 一文理解kafka?rebalance負載均衡

    一文理解kafka?rebalance負載均衡

    這篇文章主要為大家介紹了kafka?rebalance負載均衡的深入理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • 淺談java7增強的try語句關閉資源

    淺談java7增強的try語句關閉資源

    下面小編就為大家?guī)硪黄獪\談java7增強的try語句關閉資源。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • Spring基礎篇之初識DI和AOP

    Spring基礎篇之初識DI和AOP

    這篇文章主要為大家詳細介紹了Spring基礎篇之初識DI和AOP,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • 關于java的九個預定義Class對象

    關于java的九個預定義Class對象

    這篇文章主要介紹了關于java的九個預定義Class對象,在Java中,沒有類就無法做任何事情。然而,并不是所有的類都具有面向對象特征。如Math.random,并只需要知道方法名和參數(shù),需要的朋友可以參考下
    2023-05-05
  • java自帶的四種線程池實例詳解

    java自帶的四種線程池實例詳解

    java線程的創(chuàng)建非常昂貴,需要JVM和OS(操作系統(tǒng))互相配合完成大量的工作,下面這篇文章主要給大家介紹了關于java自帶的四種線程池的相關資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • mybatis-plus開啟sql日志打印的三種方法

    mybatis-plus開啟sql日志打印的三種方法

    本文主要介紹了mybatis-plus開啟sql日志打印的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-05-05
  • Java國密加密SM2代碼詳細使用步驟

    Java國密加密SM2代碼詳細使用步驟

    SM2算法可以用較少的計算能力提供比RSA算法更高的安全強度,而所需的密鑰長度卻遠比RSA算法低,下面這篇文章主要給大家介紹了關于Java國密加密SM2代碼的相關資料,需要的朋友可以參考下
    2024-07-07
  • java按指定編碼寫入和讀取文件內容的類分享

    java按指定編碼寫入和讀取文件內容的類分享

    這篇文章主要介紹了java按指定編碼寫入和讀取文件內容的類,需要的朋友可以參考下
    2014-02-02

最新評論