根据key 从yml 获取具体值的工具类

2022-08-16 08:17:28 浏览数 (1)

这里写目录标题

  • 1 工具类

1 工具类

代码语言:javascript复制
public class YamlUtil {

//    public static final YamlUtil instance = new YamlUtil();
    private static Map<String, Map<String, Object>> ymlMap = new HashMap<>();

    static {
         Yaml yaml = new Yaml();
         try (InputStream in = YamlUtil.class.getClassLoader().getResourceAsStream("bootstrap.yml");) {
                 ymlMap = yaml.loadAs(in, HashMap.class);
             } catch (Exception e) {
             }
    }
    public static String getValue(String key) {
         String separator = ".";
         String[] separatorKeys = null;
         if (key.contains(separator)) {
                 separatorKeys = key.split("\.");
             } else {
                 return ymlMap.get(key).toString();
             }
         Map<String, Object> finalValue = new HashMap<>();
         for (int i = 0; i < separatorKeys.length - 1; i  ) {
                 if (i == 0) {
                         finalValue = ymlMap.get(separatorKeys[i]);
                         continue;
                     }
                if (finalValue == null) {
                         break;
                    }
                 finalValue = (Map) finalValue.get(separatorKeys[i]);
             }
         return finalValue == null ? null : finalValue.get(separatorKeys[separatorKeys.length - 1]).toString();
    }

    public static void main(String[] args) {
        String value = YamlUtil.getValue("feign.client.default-config.read-timeout");
        System.out.println(value);
    }
}

0 人点赞