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);
}
}
参考