使用Java編寫一個(gè)好用的解析配置工具類
需求一: 加載解析 .properties 文件
對(duì)于一個(gè) .properties 配置文件,如何用 Java 加載讀取并解析其中的配置項(xiàng)呢?
方式一: 直接使用 JDK 自帶的 Properties
Map 接口實(shí)現(xiàn)類 —— Properties
基本介紹 & 常用方法
- Properties 類繼承自 Hashtable 類并且實(shí)現(xiàn)了 Map 接口,也是使用一種鍵值對(duì)的形式來保存形式
- 使用特點(diǎn)和 Hashtable 類似
- 用于存儲(chǔ)
xxx.properties文件中,加載數(shù)據(jù)到 Properties 類對(duì)象進(jìn)行讀取和修改 xxx.properties通常被作為配置文件- 通過 k-v 形式存放數(shù)據(jù),但是
key和value不能為null
Properties類常用方法
public class PropertiesAPIs {
public static void main(String[] args) {
Properties properties = new Properties();
//增加
// properties.put(null, "abc"); 報(bào)錯(cuò)NullPointerException
// properties.put("a", null); 報(bào)錯(cuò)NullPointerException
properties.put("john", 100);
properties.put("wakoo", 100);
properties.put("john", 11); //相同的 key 會(huì)覆蓋
System.out.println("properties =" + properties);
System.out.println(properties.get("john")); //11
System.out.println(properties.get("wakoo")); //100
}
}
解析 Properties 配置文件 - 基于 load 方法
load: 加載配置文件鍵值對(duì)到Properties對(duì)象list: 將數(shù)據(jù)顯示到指定設(shè)備getProperty(key): 根據(jù)鍵獲取值setProperty(key,value): 設(shè)置鍵值對(duì)到Properties對(duì)象store將 Properties 中的鍵值對(duì)存儲(chǔ)到配置文件,IDEA中如果保存的信息含有中文,會(huì)自動(dòng)存儲(chǔ)為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
//設(shè)置屬性
properties.setProperty("user", "Wakoo");
System.out.println(properties.get("user")); //Wakoo
//設(shè)置中文并且寫入到 .properties 文件
properties.setProperty("user", "加瓦編程");
//中文默認(rèn)會(huì)以 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"));
}
}
輸出結(jié)果

方式二: 基于 Hutools - Props 包裝工具類
參考文檔
對(duì) Properties做了簡單的封裝,提供了方便的構(gòu)造方法
常用方法
Props(): 構(gòu)造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): 獲取字符串型屬性值,若獲得的值為不可見字符使用默認(rèn)值setProperty(String key, Object value): 設(shè)置值,無給定鍵則創(chuàng)建。設(shè)置周未持久化store(String absolutePath): 持久化當(dāng)前設(shè)置,覆蓋方式propertyNames(): 繼承自Properties獲取所有配置名稱entrySet(): 繼承自HashTable得到Entry集,用于遍歷
示例
導(dǎo)入依賴
<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");
測(cè)試
public class HutoolProps {
public static void main(String[] args) throws IOException {
//加載方式一: 基于 InputStream
// InputStream in = HutoolProps.class.getResourceAsStream("/mysql.properties");
// Props props = new Props();
//加載方式二: 基于絕對(duì)路徑字符串, 支持定義編碼
Props props = new Props("mysql.properties", StandardCharsets.UTF_8);
//加載方式三: 傳入 Properties 對(duì)象
// Properties properties = new Properties();
// properties.load(new FileReader("src/main/resources/mysql.properties"));
// Props props = new Props(properties);
//還有其他方式....
//獲取單個(gè)配置項(xiàng)
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("---- 遍歷所有配置項(xiàng) ----");
for (Map.Entry<Object, Object> entry : entries) {
System.out.println("key:" + entry.getKey() + " -> value:" + entry.getValue());
}
System.out.println("--------");
//設(shè)置值,無給定鍵創(chuàng)建之。設(shè)置后未持久化
props.setProperty("ip", "127.0.0.1");
//若為 true, 配置文件更變時(shí)自動(dòng)修改
/*
啟動(dòng)一個(gè) 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);
}
}輸出結(jié)果

需求二: 加載解析 .yaml/.yml 文件
支持讀取 application.yml、application.yaml 等不同格式的配置文件。
方法: 基于 SnakeYAML 工具
參考文檔
常用方法
Yaml(): 構(gòu)造器Yaml(BaseConstructor constructor): 構(gòu)造器,自動(dòng)檢測(cè)對(duì)象類型,借助 load() 可反序列化為相關(guān)類型對(duì)象load(InputStream io): 基于 InputStream 加載單個(gè) YAML 文件load(Reader io): 基于 Reader 加載單個(gè) YAML 文件load(String yaml): 基于路徑字符串加載單個(gè) YAML
示例
a. 導(dǎo)入依賴
<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
測(cè)試 - 基于 InputStream 加載**
public class YamlUtils {
public static void main(String[] args) {
//基于 SankeYaml 工具類完成轉(zhuǎn)換
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));
}
}
}
輸出結(jié)果

測(cè)試 - 基于 Reader 加載并直接封裝返回目標(biāo)類型
a. 創(chuàng)建目標(biāo)類型 DbConfig和 application.yml內(nèi)配置一一對(duì)應(yīng)
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.測(cè)試類
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 依賴包內(nèi) 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 配置, 自動(dòng)轉(zhuǎn)換為 DbConfig
dbConfig = yaml.load(reader);
System.out.println(dbConfig);
//查詢 DbConfig 對(duì)象屬性
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);
}
}
輸出結(jié)果

到此這篇關(guān)于使用Java編寫一個(gè)好用的解析配置工具類的文章就介紹到這了,更多相關(guān)Java解析配置工具類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot @Configuration與自動(dòng)配置詳解
這篇文章主要介紹了SpringBoot中的@Configuration自動(dòng)配置,在進(jìn)行項(xiàng)目編寫前,我們還需要知道一個(gè)東西,就是SpringBoot對(duì)我們的SpringMVC還做了哪些配置,包括如何擴(kuò)展,如何定制,只有把這些都搞清楚了,我們?cè)谥笫褂貌艜?huì)更加得心應(yīng)手2022-07-07
Spring-IOC容器-Bean管理-基于XML方式超詳解
這篇文章主要介紹了Spring為IOC容器Bean的管理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-08-08
淺談java7增強(qiáng)的try語句關(guān)閉資源
下面小編就為大家?guī)硪黄獪\談java7增強(qiáng)的try語句關(guān)閉資源。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
關(guān)于java的九個(gè)預(yù)定義Class對(duì)象
這篇文章主要介紹了關(guān)于java的九個(gè)預(yù)定義Class對(duì)象,在Java中,沒有類就無法做任何事情。然而,并不是所有的類都具有面向?qū)ο筇卣?。如Math.random,并只需要知道方法名和參數(shù),需要的朋友可以參考下2023-05-05

