目录
手动
/**
* 重新加载配置文件
*/
@RequestMapping(value="refresh")
public void refresh(HttpServletRequest request){
XmlWebApplicationContext context =
(XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
context.refresh();
}
自动
pom.xml
<!--监控+refresh配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
application.properties
server.port=8080
local.test=helloworld
#management.security.enabled=false
management.endpoints.web.exposure.include=*
TestController
package com.xiaoyu.autorefresh.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class TestController {
private static int port;
@Value("${server.port}")
public void setPort(int port){
this.port = port;
}
@GetMapping("/test/port")
public int port(){
return port;
}
}
方式3
一、原理说明
实现依赖spring cloud的ContextRefresher对象和文件监听器
二、实现思路
1、使用apache的commons-io的文件监听器来监控配置文件是否变动,当配置文件变动后调用contextRefresher.refresh()方法使Spring重新加载配置信息
2、在需要支持配置变化的使用类添加@RefreshScope注解用来表示该类下的@Value需要更新配置信息
3、spring boot的scheduled会因为refresh()方法而失效,所以需要调度类继承ApplicationListener接口并在刷新事件变更后调用一次调度方法即可
三、实现方法
1、添加commons-io依赖
2、编写一个文件监听启动类继承CommandLineRunner接口在run()方法中启动文件监听器
FileAlterationMonitor monitor = new FileAlterationMonitor(1000);
FileAlterationObserver observer = new FileAlterationObserver(file);
observer.addListener(new ConfigFileListener());
monitor .addObserver(observer);
monitor.start();
3、编写一个ConfigFileListener类继承FileAlterationListenerAdaptor,在onFileChange()方法中调用
contextRefresher.refresh()即可
4、优化代码发所有的配置类尽量走配置类,在配置类添加@RefreshScope注解
5、在调度类添加ApplicationListener接口在onApplicationEvent()实现方法中调用一次调度类
this.myScheduled();