现象
版本说明:
springboot:2.2.2.RELEASE
springcloud:2.2.2.RELEASE
测试代码:
@Slf4j
public class ReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
static final AtomicInteger count = new AtomicInteger();
static {
log.info("static test");
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
log.info("监听到ready事件,第{}次", count.incrementAndGet());
}
}
//在META-INFO文件下,spring.factories文件中加入
org.springframework.context.ApplicationListener=com.demo.springbootdemo.event.ReadyEventListener
测试结果:
共监听到三次ready事件。
解决方案
以下每一项修改都可以解决:
- 将ReadyEventListener使用@Component注入,而非通过spring.factories注入。
- 移除springcloud依赖
- 升级springboot/springcloud版本(springboot 2.4及以上)
出现原因
旧版springcloud(2.x.x)带来的问题:
旧版springcloud(2.x.x)运行时会优先于springboot进行一次content初始化,并发布一次ready事件。加上后续的springboot初始化content,会发布第二次ready事件。
- 初始化content前发布start event
- prerare environment时发布prepare事件
- springcloud 监听prepare事件,调用自己的content生成方法
此时content的beanfactory中仅有少量的与springcloud相关的bean被初始化:
随后便第一次发布了ready 事件
此后回到Springboot初始化content动作(从null开始):第二次发布ready事件。(补充:springcloud 初始化后的content会被封装到Initializer中,在后续被重新释放出来。)
spring.factories带来的问题:
使用component注册ReadyEventListener并不会出现问题:该bean在spring boot容器初始化后才处理,此时只会监听到一次ready事件。
spring.factories注册优先级极高,会导致其指定的bean优先初始化(优先于content初始化),从而监听到两次ready事件。
对于ApplicationContextInitializer.class与ApplicationListener.class在应用run之前便已初始化
新版Springboot解决方案:
直接为springcloud定制化开发初始化语句,后续通过listener导入到content中。