SpringBoot 实现代码修改application.yaml,并动态刷新代码中的配置

1.修改配置文件

  • 引入依赖

    # Gradle 配置
    implementation group: 'org.yaml', name: 'snakeyaml', version: '1.23'
    
  • 读取application.yaml文件

    TestController.class.getClassLoader().getResource("application.yaml");
    
  • 修改文件

    // 读取配置
    String src = EsUserController.class.getClassLoader().getResource("application.yaml").getPath();
    Yaml yaml = new Yaml();
    FileWriter fileWriter;
    FileInputStream fileInputStream = new FileInputStream(new File(src));
    Map<String, Object> yamlMap = yaml.load(fileInputStream);
    Map<String, Object> esMap = (Map<String, Object>) yamlMap.get("elasticsearch");
    // 修改配置
    esMap.put("password", "password");
    // 字符输出
    fileWriter = new FileWriter(new File(src));
    // 用yaml方法把map结构格式化为yaml文件结构
    // 重新写入yaml文件
    fileWriter.write(yaml.dumpAsMap(yamlMap));
    // 刷新
    fileWriter.flush();
    // 关闭流
    fileWriter.close();
    fileInputStream.close();
    

完整代码

public void updateYamlFile() throws IOException {
        String src = EsUserController.class.getClassLoader().getResource("application.yaml").getPath();
        Yaml yaml = new Yaml();
        FileWriter fileWriter;
        FileInputStream fileInputStream = new FileInputStream(new File(src));
        Map<String, Object> yamlMap = yaml.load(fileInputStream);
        Map<String, Object> esMap = (Map<String, Object>) yamlMap.get("elasticsearch");
        esMap.put("password", "password");
        //字符输出
        fileWriter = new FileWriter(new File(src));
        //用yaml方法把map结构格式化为yaml文件结构
        fileWriter.write(yaml.dumpAsMap(yamlMap));
        //刷新
        fileWriter.flush();
        //关闭流
        fileWriter.close();
        fileInputStream.close();
    }

2.动态刷新配置

2.1 创建配置类

@Component
@ConfigurationProperties(prefix="elasticsearch")
public class ESConfig {

    private String host;
    private int port;
    private String user;
    private String password;

		// ... 省略getter() setter()
}

2.2 使用配置类

@RestController
public class EsUserController {

		@Autowired
		private ContextRefresher contextRefresher;		
		@Autowired
		private EsConfig esConfig;

		@GetMapping("/api/refresh")
		public void refresh() {
				// 修改配置文件
				updateYamlFile();
				// 刷新配置文件
				contextRefresher.refresh();
				// 使用刷新后的配置
				System.out.print(esconfig.password)
		}

}

2.3 具体

添加依赖

implementation group: 'org.springframework.cloud', name: 'spring-cloud-context', version: '2.2.6.RELEASE'

借助org.springframework.cloud.context.refresh.ContextRefresher 这个类来实现配置刷新

使用时候直接注入 ContextRefresher, 调用refresh() 方法进行刷新配置

参考文章:

spring boot项目如何通过代码去修改yml里面配置项的值?

SpringBoot 动态加载配置文件及刷新Bean

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐