解决Yaml类的嵌套Map,将其转为key-value格式

缘由:

因为加载顺序的问题,@Value、@Autowired这些都用不了,而我又需要读xxx.yml的配置文件,我就通过映射直接读取配置文件,得到一个Yaml对象(load),但是我发现,这个对象(load)不是我想要的效果,读取太麻烦,如下图,格式是一种嵌套的格式,想要获取其中一个参数很麻烦,而如果能转为key-value这种格式进行读取那么就方便很多。
在这里插入图片描述

解决方法:

import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

public class YamlUtils {

    private Map<String,Object> resultMap;

    private String tempKey="";

    public YamlUtils(){
        resultMap=new LinkedHashMap<>();
    }

    private void SwitchYmalMapToMap(Object map){
        if (!(map instanceof Map)) {
            String substring = tempKey.substring(0, tempKey.length() - 1);
            resultMap.put(substring,map);
            return;
        }

        for (String key:((Map<String, Object>) map).keySet()){
            tempKey += key+".";
            SwitchYmalMapToMap(((Map<String, Object>) map).get(key));
            tempKey=tempKey.substring(0,tempKey.length()-(key.length()+1));
        }
    }

    public Map<String,Object> getYamlMap(String resources) throws IOException {
        Yaml yaml = new Yaml();
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(resources);
        if (StringUtils.isEmpty(resources)){
            return null;
        }
        if (resourceAsStream==null){
            return null;
        }
        Map load = yaml.load(resourceAsStream);
        if (load==null||load.isEmpty()){
            resourceAsStream.close();
            return null;
        }
        SwitchYmalMapToMap(load);
        resourceAsStream.close();
        return this.resultMap;
    }

}

然后直接调用传入配置文件名称就可以直接读取了,不会因容器加载顺序而导致读不到配置文件
在这里插入图片描述

实现之后的效果:
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值