共计 2473 个字符,预计需要花费 7 分钟才能阅读完成。
因为工夫关系,仅记录要点:
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
正文完