springboot 启动前动态修改yaml配置文件值并使之生效

一、引入yaml文件相关的包spring

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.23</version>
</dependency>

二、在启动类中添加相关调用的代码,yaml提供的load()方法加载文件内容,再经过dump()方法回写内容。如下例子为修改springboot jackson时间时区springboot

/**
 * 动态修改注入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();
    }
}