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(); } }