Spring中event事件执行顺序

在这里插入图片描述

前言

我们自定义监听spring event通常有两种方式,先说下这两种方式,然后从两种方式的差异说明event的顺序。
在这里插入图片描述

@Component 实现

  1. 使用@Component方式实现如下:

@Component
@Slf4j
public class ApplicationListenerImpl implements ApplicationListener<ApplicationEvent> {
    
    

    public ApplicationListenerImpl() {
    
    
        System.out.println("ApplicationListenerImpl#constructor");
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
    
    
        System.out.println("ApplicationListenerImpl#" + event.getClass().getSimpleName());
    }
}
  1. java 启动类
@SpringBootApplication
public class ListenerApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(ListenerApplication.class, args).close();
    }

}
  1. 执行结果如下:
    在这里插入图片描述

spring.factories实现

  1. 实现类

public class ApplicationListenerImpl2 implements ApplicationListener<ApplicationEvent> {
    
    

    public ApplicationListenerImpl2() {
    
    
        System.out.println("ApplicationListenerImpl#constructor");
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
    
    
        System.out.println("ApplicationListenerImpl2#" + event.getClass().getSimpleName());
    }
}
  1. spring.factories 如下
org.springframework.context.ApplicationListener=fast.cloud.nacos.listener.ApplicationListenerImpl2

  1. 运行结果如下:

在这里插入图片描述
在这里插入图片描述

发现ContextRefreshedEvent之前的四个也是可以监听到的,分析下源码。

源码分析

SpringApplication 构造方法中,就调用 getSpringFactoriesInstances 来获取 /META-INF/spring.factories 配置的 ApplicationListener,代码如下:

在这里插入图片描述

SpringFactoriesLoader#loadFactoryNames 实现了从该配置文件获取实现名的方法。从这之后就能收到后续触发的事件。

通过 @Component 方式时,在 SpringApplication#refresh 中调用 registerListeners 获取的所有 ApplicationListener 接口的实现。代码如下:

在这里插入图片描述

在这里插入图片描述

cloud是什么时候注册的

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

得出结论可以看到cloud是监听ServletWebServerInitializedEvent时,去做服务注册的,这样有问题么,下篇将会给出在实际应用过程中遇到的问题及方案。

参考文章

不懂SpringApplication生命周期事件?那就等于不会Spring Boot嘛

Guess you like

Origin blog.csdn.net/qq_37362891/article/details/119787529