1、引入yaml文件相关的包
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
2、在启动类中添加相关调用的代码,yaml提供的load()方法加载文件内容,再通过dump()方法回写内容。以下例子为修改springboot jackson时间时区
/**
* 动态修改注入yaml配置文件的值
*/
private static void dynamicUpdateYaml(){
try {
Map m1,m2,m3;
Yaml yaml = new Yaml();
File file = new File(StarterApplication.class.getClassLoader().getResource("config/application.yaml").getFile());
m1 = (Map) yaml.load(new FileInputStream(file));
m2 = (Map) m1.get("spring");
m3 = (Map) m2.get("jackson");
m3.put("time-zone", System.getProperty("user.timezone"));
m3.put("locale", System.getProperty("user.country"));
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(yaml.dump(m1));
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

本文介绍了一种在Spring Boot应用中动态修改YAML配置文件的方法,通过读取、修改并重新写入YAML文件,实现运行时调整配置,如修改Jackson的时间区域设置。
670

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



