springboot 啓動前動態修改yaml配置文件值並使之生效

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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章