spring boot 读取yml配置

本文分享了一个用于读取和解析SpringBoot项目中YAML配置文件的工具类,该工具类能够将YAML配置转换为Map集合,方便在项目中进行配置项的获取和使用。

spring boot 官方文档
spring boot官方文档推荐使用yml代替properties进行配置,自己写了个读取yml配置的工具类,分享一下

package com.dirk.commons.util;

import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Dirk
 * @Description yaml配置工具类
 * @Date 2019-08-19 11:01
 */
public class YamlUtil {

    private static final String DEV = "dev";
    private static final String OS_LINUX = "linux";
    private static Map<String, Object> map = new HashMap<>();

    /**
     * 加载yaml配置转换为{@code Map<String, Object>}
     *
     * @param fileName
     * @return
     */
    private static Map<String, Object> loadYamlByFileName(String fileName) {
        YamlMapFactoryBean yaml = new YamlMapFactoryBean();
        yaml.setResources(new ClassPathResource(fileName));
        forEachYaml("", yaml.getObject());
        return map;
    }

    @SuppressWarnings({"unchecked"})
    private static void forEachYaml(String key, Map<String, Object> yaml) {
        if (yaml == null) {
            return;
        }
        yaml.forEach((s, o) -> {
            if (!StringUtils.isEmpty(key)) {
                s = key.concat(".").concat(s);
            }
            if (o instanceof Map) {
                forEachYaml(s, (Map<String, Object>) o);
            } else {
                map.put(s, o);
            }
        });
    }

    public static Object getObject(String key) {
        Map<String, Object> yaml = loadYamlByFileName("application.yml");
        String config = (String) yaml.get("spring.profiles.active");
        if (!StringUtils.isEmpty(config)) {
            String fileName = "application-".concat(config).concat(".yml");
            yaml.putAll(loadYamlByFileName(fileName));
        }
        return map.get(key);
    }

    /**
     * 获取yaml配置的值
     *
     * @param key key
     * @return value
     */
    public static String get(String key) {
        return (String) getObject(key);
    }

    /**
     * 是否是dev环境
     *
     * @return
     */
    public static Boolean isDev() {
        return DEV.equals(get("spring.profiles.active"));
    }

    /**
     * 是否是pro环境
     *
     * @return
     */
    public static Boolean isPro() {
        return !isDev();
    }

    /**
     * 是否是本地环境
     *
     * @return
     */
    public static Boolean isLocal() {
        String os = System.getProperty("os.name");
        return !os.toLowerCase().contains(OS_LINUX);
    }
}

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值