使用Java编写一个好用的解析配置工具类

 更新时间:2024年11月03日 10:06:57   作者:jooLs薯薯熹  
这篇文章主要为大家详细介绍了如何使用Java编写一个好用的解析配置工具类,支持解析格式有properties,yaml和yml,感兴趣的可以了解下

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

对于一个 .properties 配置文件,如何用 Java 加载读取并解析其中的配置项呢?

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

Map 接口实现类 —— Properties

基本介绍 & 常用方法

  • Properties 类继承自 Hashtable 类并且实现了 Map 接口,也是使用一种键值对的形式来保存形式
  • 使用特点和 Hashtable 类似
  • 用于存储 xxx.properties 文件中,加载数据到 Properties 类对象进行读取和修改
  • xxx.properties 通常被作为配置文件
  • 通过 k-v 形式存放数据,但是 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: 将数据显示到指定设备
  • 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 文件

支持读取 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");

        //可直接封装成 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. 创建目标类型 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解析配置工具类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 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语句关闭资源

    下面小编就为大家带来一篇浅谈java7增强的try语句关闭资源。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • Spring基础篇之初识DI和AOP

    Spring基础篇之初识DI和AOP

    这篇文章主要为大家详细介绍了Spring基础篇之初识DI和AOP,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • 关于java的九个预定义Class对象

    关于java的九个预定义Class对象

    这篇文章主要介绍了关于java的九个预定义Class对象,在Java中,没有类就无法做任何事情。然而,并不是所有的类都具有面向对象特征。如Math.random,并只需要知道方法名和参数,需要的朋友可以参考下
    2023-05-05
  • java自带的四种线程池实例详解

    java自带的四种线程池实例详解

    java线程的创建非常昂贵,需要JVM和OS(操作系统)互相配合完成大量的工作,下面这篇文章主要给大家介绍了关于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

最新评论