使用Java编写一个好用的解析配置工具类
目录
- 需求一: 加载解析 .properties 文件
- 方式一: 直接使用 JDK 自带的 Properties
- 方式二: 基于 Hutools - Props 包装工具类
- 需求二: 加载解析 .yaml/.yml 文件
- 方法: 基于 SnakeYAML 工具
需求一: 加载解析 .properties 文件
对于一个 .properties 配置文件,如何用 Java 加载读取并解析其中的配置项呢?
方式一: 直接使用 JDK 自带的 Properties
Map 接口实现类 —— Properties
基本介绍 & 常用方法
- Properties 类继承自 Hashtable 类并且实现了 Map 接口,也是使用一种键值对的形式来保存形式
- 使用特点和 Hashtable 类似
- 用于存储
xxx.properties文件中,加载数据到 Properties 类对象进行读取和修改 xxx.properties通常被作为配置文件- 通过 k-v 形式存放数据,但是
key和value不能为null
Properties类常用方法
public class PropertiesAPIs {
public static void main(String[]javascript 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: 将数据显示到指定设备getProperty(key): 根据键获取值setProperty(key,value): 设置键值对到Properties对象store将 Properties 中的键值对存储到配置文件,IDEA中如果保存的信息含有中文,会自动存储为Unicode码
示例
a. 创建一份 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): 静态方法,获取Classpath下的Proeprties文件getProp(Resource resource, Charset charset): 静态方法,作用同上,可指定编码load(Resource resource): 初始化配置文件getStr(String key): 获取字符串型属性值getStr(String key, String defaultValue): 获取字符串型属性值,若获得的值为不可见字符使用默认值setProperty(String key, Object value): 设置值,无给定键则创建。设置周未持久化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("--------");
//设置值,无给定键创建之。设置后未持久化
props.setProperty("ip", "127.0.0.1");
//若为 true, 配置文件更变时自动修改
/*
启动一个 SimpleWatcher 线程监控
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 文件gpWOUiZYJH
支持读取 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. 创建 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")http://www.devze.com;
//可直接封装成 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. 创建目标类型 DbConfig和 application.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 = n编程ew FileReader("src/main/resources/application.yml")) {
//加载 yaml 配置, 自动转换为 DbConfig
dbConfig = yaml.load(reahttp://www.devze.comder);
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解析配置工具类内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
加载中,请稍侯......
精彩评论