springboot动态修改配置文件
Posted 岁月峥嵘走过
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot动态修改配置文件相关的知识,希望对你有一定的参考价值。
由于时间关系,仅记录要点:
1.引入 spring-boot-starter-actuator及spring-cloud-starter-config
2.对需要刷新的属性使用@Value注解,同时将类使用@RefreshScope注解进行标记
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@RestController
@RefreshScope
public class TestController {
@Autowired
private ContextRefresher contextRefresher;
@Autowired
private ConfigurableEnvironment environment;
@Value("${user.test1}")
private String test1;
@GetMapping("test1")
public String getInxo1() {
return this.test1;
}
@PostMapping("refresh")
public String default02(@RequestParam String name){
HashMap<String,Object> map = new HashMap<>();
map.put("user.test1",name);
MapPropertySource propertySource = new MapPropertySource("dynamic",map);
environment.getPropertySources().addFirst(propertySource);
new Thread(() -> contextRefresher.refresh()).start();
return "success";
}
}
3.application.properties配置。(注意2.0.3版本后暴露/refresh接入点的方式与旧版本不同,需要手动设置暴露点。)
server.port=8888
management.endpoints.web.exposure.include=refresh
user.test1="hello world"
4.测试
4.1 启动项目,访问 http://localhost:8888/test1
此时浏览器应显示 hello world
4.2 通过post请求,传参修改test1的内容 http://localhost:8888/refresh
4.3 http://localhost:8888/test1
以上是关于springboot动态修改配置文件的主要内容,如果未能解决你的问题,请参考以下文章
在SpringBoot项目中快速搭建一个Nacos配置中心,再也不用修改配置文件上传了
Springboot 使用@RefreshScope 注解,实现配置文件的动态加载