由于时间关系,仅记录要点:
1.引入 spring-boot-starter-actuator及spring-cloud-starter-config
2.对需要刷新的属性使用@Value注解,同时将类使用@RefreshScope注解进行标记
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@RefreshScope
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@Value("${server.port}")
private int port;
@RequestMapping("/port")
public int port() {
return port;
}
}
3.application.properties配置。(注意2.0.3版本后暴露/refresh接入点的方式与旧版本不同,需要手动设置暴露点。)
server.port=8888
management.endpoints.web.exposure.include=refresh
4.测试
4.1 启动项目,访问 http://localhost:8888/port
此时浏览器应显示8888
4.2 application.properties将server.port改为9999
4.3 http://localhost:8888/actuator/refresh
4.4 http://localhost:8888/port
此时浏览器应显示9999
(注意,即使刷新配置,tomcat并未重启,只是server.port对应的值产生了改变,并刷新到标明了@RefreshScope注解的类。所以访问tomcat时依然用8888端口)