使用Java編寫一個好用的解析配置工具類
需求一: 加載解析 .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ù),但是
key和value不能為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"));
}
}
輸出結(jié)果

方式二: 基于 Hutools - Props 包裝工具類
參考文檔
對 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): 獲取字符串型屬性值,若獲得的值為不可見字符使用默認值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);
}
}輸出結(jié)果

需求二: 加載解析 .yaml/.yml 文件
支持讀取 application.yml、application.yaml 等不同格式的配置文件。
方法: 基于 SnakeYAML 工具
參考文檔
常用方法
Yaml(): 構(gòu)造器Yaml(BaseConstructor constructor): 構(gòu)造器,自動檢測對象類型,借助 load() 可反序列化為相關(guān)類型對象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 工具類完成轉(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é)果

測試 - 基于 Reader 加載并直接封裝返回目標類型
a. 創(chuàng)建目標類型 DbConfig和 application.yml內(nèi)配置一一對應
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 依賴包內(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 配置, 自動轉(zhuǎn)換為 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);
}
}
輸出結(jié)果

到此這篇關(guān)于使用Java編寫一個好用的解析配置工具類的文章就介紹到這了,更多相關(guān)Java解析配置工具類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot @Configuration與自動配置詳解
這篇文章主要介紹了SpringBoot中的@Configuration自動配置,在進行項目編寫前,我們還需要知道一個東西,就是SpringBoot對我們的SpringMVC還做了哪些配置,包括如何擴展,如何定制,只有把這些都搞清楚了,我們在之后使用才會更加得心應手2022-07-07
Spring-IOC容器-Bean管理-基于XML方式超詳解
這篇文章主要介紹了Spring為IOC容器Bean的管理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2021-08-08

