java读取解析application.yml

java读取解析application.yml

不用依赖spring容器,可单独使用。
第一步、首先要2个jar


    com.fasterxml.jackson.dataformat
    jackson-dataformat-yaml
    2.9.8


    com.fasterxml.jackson.dataformat
    jackson-dataformat-properties
    2.9.8
第二步、新建一个BootYaml.java
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;
import com.ynzhongxi.pay.utils.Tools;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 写一个SpringBoot读取Yaml配置文件的类
 *
 * @author lixingwu
 */
public class BootYaml extends Yaml {
    /** 环境配置路径的键值 */
    private String active;
    /** 引入yml的键值 */
    private String include;
    /** 配置文件的前缀 */
    private String prefix;

    /**
     * 

方法名称:根据application.yml转化为LinkedHashMap.

*

详细描述:会解析spring.profiles.active启用的配置和spring.profiles.include引入的文件.

*

创建时间:2019-07-10 17:39:38

*

创建作者:李兴武

*

修改记录:

* * @param path application.yml * @return the linked hash map * @author "lixingwu" */ public LinkedHashMap loadAs(String path) { String classPath = Tools.getRootPath(); // 组合一个map,把启用的配置,引入的文件组合起来 LinkedHashMap mapAll = new LinkedHashMap<>(); LinkedHashMap mainMap = yml2Map(classPath + "/" + path); // 读取启用的配置 Object active = mainMap.get(this.active); if (!Tools.isBlank(active)) { mapAll.putAll(yml2Map(StrUtil.format("{}/{}-{}.yml", classPath, this.prefix, active))); } // 加载引入的yml Object include = mainMap.get(this.include); // include是使用逗号分隔开的,需要切割一下 List split = StrSpliter.split(Convert.toStr(include), StrUtil.C_COMMA, true, true); for (String inc : split) { mapAll.putAll(yml2Map(StrUtil.format("{}/{}-{}.yml", classPath, this.prefix, inc))); } // 主配置覆盖其他配置 mapAll.putAll(mainMap); // 把map转化为字符串 String mapString = MapUtil.joinIgnoreNull(mapAll, "\n", "="); // 再把map字符串转化为yamlStr字符串 String yamlStr = properties2YamlStr(mapString); // 使用Yaml构建LinkedHashMap return super.loadAs(yamlStr, LinkedHashMap.class); } /** *

方法名称:Yml 格式转 LinkedHashMap.

*

详细描述:转载自 https://www.cnblogs.com/xujingyang/p/10613206.html .

*

创建时间:2019-07-10 09:30:19

*

创建作者:李兴武

*

修改记录:

* * @param path Yml路径 * @author "lixingwu" */ public LinkedHashMap yml2Map(String path) { final String dot = "."; LinkedHashMap map = new LinkedHashMap<>(); // 文件不存在,置空 if (!FileUtil.exist(path)) { return map; } try { YAMLFactory yamlFactory = new YAMLFactory(); YAMLParser parser = yamlFactory.createParser(FileUtil.getUtf8Reader(path)); StringBuilder key = new StringBuilder(); String value; JsonToken token = parser.nextToken(); while (token != null) { if (!JsonToken.START_OBJECT.equals(token)) { if (JsonToken.FIELD_NAME.equals(token)) { if (key.length() > 0) { key.append(dot); } key.append(parser.getCurrentName()); token = parser.nextToken(); if (JsonToken.START_OBJECT.equals(token)) { continue; } value = parser.getText(); map.put(key.toString(), value); int dotOffset = key.lastIndexOf(dot); if (dotOffset > 0) { key = new StringBuilder(key.substring(0, dotOffset)); } } else if (JsonToken.END_OBJECT.equals(token)) { int dotOffset = key.lastIndexOf(dot); if (dotOffset > 0) { key = new StringBuilder(key.substring(0, dotOffset)); } else { key = new StringBuilder(); } } } token = parser.nextToken(); } parser.close(); return map; } catch (Exception e) { throw new RuntimeException(e); } } /** *

方法名称:Properties内容转化为yaml内容.

*

详细描述:.

*

创建时间:2019-07-10 15:06:48

*

创建作者:李兴武

*

修改记录:

* * @param content Properties内容 * @return the string * @author "lixingwu" */ public String properties2YamlStr(String content) { // 临时生成yml String filePath = Tools.getRootPath() + "/temp.yml"; JsonParser parser; JavaPropsFactory factory = new JavaPropsFactory(); try { parser = factory.createParser(content); } catch (IOException e) { throw new RuntimeException(e); } try { YAMLFactory yamlFactory = new YAMLFactory(); YAMLGenerator generator = yamlFactory.createGenerator(FileUtil.getOutputStream(filePath)); JsonToken token = parser.nextToken(); while (token != null) { if (JsonToken.START_OBJECT.equals(token)) { generator.writeStartObject(); } else if (JsonToken.FIELD_NAME.equals(token)) { generator.writeFieldName(parser.getCurrentName()); } else if (JsonToken.VALUE_STRING.equals(token)) { generator.writeString(parser.getText()); } else if (JsonToken.END_OBJECT.equals(token)) { generator.writeEndObject(); } token = parser.nextToken(); } parser.close(); generator.flush(); generator.close(); // 读取临时生成yml的内容 String ymlContent = FileUtil.readUtf8String(filePath); // 删除临时生成yml FileUtil.del(filePath); return ymlContent; } catch (Exception e) { throw new RuntimeException(e); } } public String getActive() { return active; } public void setActive(String active) { this.active = active; } public String getInclude() { return include; } public void setInclude(String include) { this.include = include; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } }

第三步、创建工具类YmlPropUtils.java

import cn.hutool.core.convert.Convert;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.StrUtil;
import com.ynzhongxi.pay.pojo.system.BootYaml;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 读取application.yml件
 *
 * @author lixingwu
 */
public class YmlPropUtils {
    private LinkedHashMap prop;
    private static YmlPropUtils ymlPropUtils = new YmlPropUtils();

    /**
     * 私有构造,禁止直接创建
     */
    private YmlPropUtils() {
        BootYaml yaml = new BootYaml();
        yaml.setActive("spring.profiles.active");
        yaml.setInclude("spring.profiles.include");
        yaml.setPrefix("application");
        prop = yaml.loadAs("application.yml");
    }

    /**
     * 获取单例
     *
     * @return YmlPropUtils
     */
    public static YmlPropUtils getInstance() {
        if (ymlPropUtils == null) {
            ymlPropUtils = new YmlPropUtils();
        }
        return ymlPropUtils;
    }

    /**
     * 根据属性名读取值
     * 先去主配置查询,如果查询不到,就去启用配置查询
     *
     * @param name 名称
     */
    public Object getProperty(String name) {
        LinkedHashMap param = prop;
        List split = StrSpliter.split(name, StrUtil.C_DOT, true, true);
        for (int i = 0; i < split.size(); i++) {
            if (i == split.size() - 1) {
                return param.get(split.get(i));
            }
            param = Convert.convert(LinkedHashMap.class, param.get(split.get(i)));
        }
        return null;
    }
}

第四步、测试一下

public static void main(String[] args) {
    Object property = YmlPropUtils.getInstance().getProperty("spring.datasource.type");
    System.out.println(property);
}

over!over!

转载于:https://www.cnblogs.com/lixingwu/p/11176942.html

你可能感兴趣的:(java读取解析application.yml)