spring boot 中怎么监听容器启动
更新:HHH   时间:2023-1-7


这篇文章给大家介绍spring boot 中怎么监听容器启动,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

自定义监听器

@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

  @Override
  public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

    // 获取spring 上下文
    ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();

    // do your work...
}

源码分析

springboot 启动应用, 执行 SpringApplication.run(String… args) 方法

run方法中执行完初始化上下文方法后, 会执行this.refreshContext方法, 刷新

经过一堆方法跳转, 执行 AbstractApplicationContextl类的publishEvent(Object event, @Nullable ResolvableType eventType) 方法

然后执行 SimpleApplicationEventMulticaster.multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType)

然后依次执行所有监听器的onApplicationEvent()方法

// 遍历所有ApplicationListeners, 依次执行ApplicationListener 的onApplicationEvent()方法
public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
  ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
  Iterator var4 = this.getApplicationListeners(event, type).iterator();

  while(var4.hasNext()) {
    ApplicationListener<?> listener = (ApplicationListener)var4.next();
    Executor executor = this.getTaskExecutor();
    if (executor != null) {
      executor.execute(() -> {
        this.invokeListener(listener, event);
      });
    } else {
      this.invokeListener(listener, event);
    }
  }

}

关于spring boot 中怎么监听容器启动就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

返回编程语言教程...