SpringCloud 配置中心帮助我们能动态地刷新应用的配置,只需要通过一个注解 @RefreshScope 即可。
一直以为 @RefreshScope 会重新启动应用,直到同事遇到问题,一起调试后才发现,事实并非如此。
验证过程非常简单,手写几个 ApplicationListener 即可。
- @Component
- public class CustomApplicationStartedListener implements ApplicationListener
{ - @Override
- public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
- // @RefreshScope 修改配置文件后,并不触发该事件,换句话说没有重启应用
- ConfigurableApplicationContext applicationContext = applicationStartedEvent.getApplicationContext();
- System.out.println("首次启动:" + applicationContext);
- Object tjClient = applicationContext.getBean("tjClient");
- System.out.println("首次启动:" + tjClient);
-
- }
- @Component
- public class CustomContextRefreshedListener implements ApplicationListener
{ - @Override
- public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
- ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
- Object tjClient = applicationContext.getBean("tjClient");
- System.out.println(tjClient);
- }
-
- }
应用启动后,刷新Nacos 上的配置文件,上面的两个 Listener 都没有走,只走了下面这个Listener
- @Component
- public class CustomRefreshScopeRefreshedListener implements ApplicationContextAware, ApplicationListener
{ -
- private ApplicationContext applicationContext;
-
- @Override
- public void onApplicationEvent(RefreshScopeRefreshedEvent refreshScopeRefreshedEvent) {
- // @RefreshScope 刷新配置文件后,发出了 refreshScopeRefreshedEvent 事件, 而没有出发 ContextRefreshedEvent
- // 换句话说 applicationContext 仍然是同一个对象
- System.out.println("刷新Nacos配置文件后:" + applicationContext);
- // @RefreshScope 注解的对象,刷新后并没有立刻重新创建,而是在首次使用时,才创建,相当于懒加载
- Object tjClient = applicationContext.getBean("tjClient");
- System.out.println("刷新Nacos配置文件后:" + tjClient);
- }
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- this.applicationContext = applicationContext;
- }
- //RefreshScopeRefreshedEvent
- }
打印结果也说明了 刷新配置文件时,applicationContext 并没有重建,应用没有重启!!
