ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java yaml配置文件读取工具类

2022-06-16 11:36:05  阅读:191  来源: 互联网

标签:Java String 配置文件 fileName yaml static key return yml


简介

用习惯了SpringBoot框架来读取yaml配置,突然转到非Spring的普通java项目,读取配置文件有点麻烦。为了能像之前用SrpingBoot一样使用yaml,所以网上找了下类似的工具类,新增了主动设置profile方法。
而且有时候即使在Springboot框架下,使用这种工具类还有一个好处,因为springboot自动加载配置的动作在静态代码块之后,所以会取不到配置。当在static代码块中获取配置时,要拿到配置值就要靠工具类去主动加载配置,而不是等待spring。

配置位置

支持读取${}占位符中的内容

Maven

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.26</version>
</dependency>

ReadYmlUtil.class

/**
 * @Deacription 支持读取${}占位符中的内容
 * @Author levi
 * @Date 2022/06/16 9:43
 * @Version 1.0
 **/
public class ReadYmlUtil {

    // ${} 占位符 正则表达式
    private static Pattern p1 = Pattern.compile("\\$\\{.*?\\}");

    private ReadYmlUtil(){
        throw new AssertionError();
    }

    /**
     * key:文件索引名
     * value:配置文件内容
     */
    private static Map<String , LinkedHashMap> ymls = new HashMap<>();
    /**
     * String:当前线程需要查询的文件名
     */
    private static ThreadLocal<String> nowFileName = new InheritableThreadLocal<>();

    private static ThreadLocal<String> profileLocal = new InheritableThreadLocal<>();

    /**
     * 主动设置,初始化当前线程的环境
     * @param profile
     */
    public static void setProfile(String profile) {
        profileLocal.set(profile);
    }

    /**
     * 加载配置文件
     * @param fileName
     */
    private static void loadYml(String fileName){
        nowFileName.set(fileName);
        if (!ymls.containsKey(fileName)){
            ymls.put(fileName , new Yaml().loadAs(ReadYmlUtil.class.getResourceAsStream("/" + fileName),LinkedHashMap.class));
        }
    }

    /**
     * 读取yml文件中的某个value。
     * 支持解析 yml文件中的 ${} 占位符
     * @param key
     * @return Object
     */
    private static Object getValue(String key){
        String[] keys = key.split("[.]");
        Map ymlInfo = (Map) ymls.get(nowFileName.get()).clone();
        for (int i = 0; i < keys.length; i++) {
            Object value = ymlInfo.get(keys[i]);
            if (i < keys.length - 1){
                ymlInfo = (Map) value;
            }else if (value == null){
                throw new RuntimeException("key不存在");
            }else {
                String g;
                String keyChild;
                String v1 = (String)value;
                for(Matcher m = p1.matcher(v1); m.find(); value = v1.replace(g, (String)getValue(keyChild))) {
                    g = m.group();
                    keyChild = g.replaceAll("\\$\\{", "").replaceAll("\\}", "");
                }
                return value;
            }
        }
        return "";
    }

    /**
     * 读取yml文件中的某个value
     * @param fileName  yml名称
     * @param key
     * @return Object
     */
    public static Object getValue(String fileName , String key){
        loadYml(fileName);
        return getValue(key);
    }

    /**
     * 框架私有方法,非通用。
     * 获取 spring.profiles.active的值: test/prod 测试环境/生成环境
     * @return
     */
    public static String getProfiles(){
        if (profileLocal.get() == null) {
            String value = (String) getValue("application.yml", "spring.profiles.active");
            setProfile(value);
        }
        return profileLocal.get();
    }

    /**
     * 读取yml文件中的某个value,返回String
     * @param fileName
     * @param key
     * @return String
     */
    public static String getValueToString(String fileName , String key){
        return (String)getValue(fileName , key);
    }

    /**
     *  获取 application.yml 的配置
     * @param key
     * @return
     */
    public static String getValueToString(String key){
        return (String)getValue("application.yml" , key);
    }

    /**
     *  获取 application-test/prod.yml 的配置
     * @param key
     * @return
     */
    public static String getProfileValueToString(String key){
        String fileName = "application-" + getProfiles() + ".yml";
        return (String)getValue(fileName , key);
    }

    /**
     * Test
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(getProfiles());
        System.out.println(ReadYmlUtil.getValueToString("pulsar.topic"));//get application.yml
        System.out.println(ReadYmlUtil.getValueToString("your-yaml-file-name.yml", "key1.key2"));//get other yml
        System.out.println(ReadYmlUtil.getProfileValueToString("Ignite-addr"));// get application-${profile}.yml

        ReadYmlUtil.setProfile("test"); //主动修改环境配置
        System.out.println(ReadYmlUtil.getProfileValueToString("Ignite-addr"));// get application-${profile}.yml
    }


}

标签:Java,String,配置文件,fileName,yaml,static,key,return,yml
来源: https://www.cnblogs.com/levi125/p/16381320.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有