最近在写一个工具类,在测试时发现main内无法使用自动注入获取配置文件yml属性值。于是查阅相关资料,手写了yml工具类,用于在无法使用spring自动注入时手动获取yml属性。
相关代码如下:
import com.google.common.collect.Maps;
import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
public class YmlUtils {
private static final String YML = "application.yml";
private static final Map<String, Object> ymlMap = Maps.newConcurrentMap();
static {
getApplicationYml(YML);
getApplicationYml(getActiveYml());
}
private static String getActiveYml() {
String[] strings = YML.split("\\.");
return strings[0] + "-" + ymlMap.get("spring.profiles.active") + "." + strings[1];
}
private static void getApplicationYml(String yml) {
Yaml yaml = new Yaml();
URL url = ClassLoader.getSystemResource(yml);
try (FileInputStream in = new FileInputStream(url.ge

本文介绍了一个在main方法中无法使用Spring自动注入时,如何通过编写YmlUtils类来手动读取并获取YAML配置文件属性的解决方案。代码示例展示了如何加载并解析`application.yml`,将属性值存储到并发安全的Map中,以便在程序中方便地获取配置值。

1万+

被折叠的 条评论
为什么被折叠?



