由于时间关系,仅记录要点:
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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。