配置变更监听
EnvironmentChangeEvent 是 Spring Framework 中的一个事件类型,用于表示环境变更的事件。
在 Spring 应用程序中,Environment 是负责管理配置属性的中心组件。当应用程序的配置属性发生变化时,Spring 会触发 EnvironmentChangeEvent 事件,以通知相关的监听器进行相应的处理。
EnvironmentChangeEvent 提供了一种机制,使应用程序能够响应配置属性的变化,并采取适当的行动。例如,您可以编写一个监听器来捕获 EnvironmentChangeEvent,并在配置属性发生变化时执行特定的逻辑,例如重新加载配置或重新初始化相关的组件。
@RestController
public class DemoController {
@Autowired
private ContextRefresher contextRefresher;
@Autowired
private BizConfig bizConfig;
@Autowired
private ValueConfig valueConfig;
@Value("${rest.uuid}")
private String uuid;
@GetMapping(path = "/show")
public String show() {
JSONObject res = new JSONObject();
res.put("biz", JSONObject.toJSONString(bizConfig));
res.put("uuid", valueConfig.getUuid());
res.put("no-refresh", uuid);
return res.toJSONString();
}
@GetMapping(path = "/refresh")
public String refresh() {
new Thread(() -> contextRefresher.refresh()).start();
return show();
}
@EventListener
public void envListener(EnvironmentChangeEvent event) {
System.out.println("conf change: " + event);
}
}
在配置属性发生变化时控制台打印如下:
conf change: org.springframework.cloud.context.environment.EnvironmentChangeEvent[source=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4b2b04b7, started on Sun Dec 17 16:47:59 CST 2023]