示例:

在Spring中,事件机制采用观察者模式进行具体实现,设计类图如下:Spring的事件监听(Event-Listener)机制 - 图1

来自 Spring事件监听机制

来看看一个简单的自定义事件/监听器示例, 来自 Spring源码-事件监听机制(实现EventListener接口)

1、事件定义

  1. /**
  2. * 定义事件类型
  3. *
  4. * @author lihongmin
  5. * @date 2019/11/3 20:30
  6. */
  7. public class OrderEvent extends ApplicationEvent {
  8. public OrderEvent(Object source) {
  9. super(source);
  10. }
  11. }

2、事件监听(泛型)

/**
 *  订单事件监听
 * @author lihongmin
 * @date 2019/11/3 20:33
 */
@Component
public class OrderEventListener implements ApplicationListener<OrderEvent> {

    @Override
    public void onApplicationEvent(OrderEvent orderEvent) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("我收到了一个事件:" + orderEvent.getSource());
    }
}

上面注意别忘了给 Listener 加上@Component 注解了。

3、模拟事件发送

/**
 *  事件触发模拟
 *
 *  我受到了一个事件:我发布了事件!!!
 *  我执行完毕了!!!
 *
 * @author lihongmin
 * @date 2019/11/3 20:35
 */
@Controller
public class OrderEventController implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @ResponseBody
    @GetMapping("publishOrderEvent")
    public String publishOrderEvent() {
        applicationContext.publishEvent(new OrderEvent("我发布了事件!!!"));
        System.out.println("我执行完毕了!!!");
        return "发送事件了!";
    }
}

4、启动项目,调用 127.0.0.1:8080/publishOrderEvent

我收到了一个事件:我发布了事件!!!
我执行完毕了!!!

总结:事件发送非常的简单,一个事件类型,一个监听,一个触发机制。并且该事件为同步机制(后续在Spring Boot中可以方便切换为异步)。

Spring事件原理

Spring事件机制是观察者模式的一种实现,但是除了发布者 (Publisher) 和监听者 (Listener) 两个角色之外,还有一个 EventMultiCaster (翻译为事件多播器) 的角色负责把事件转发给监听者,工作流程如下:

Spring的事件监听(Event-Listener)机制 - 图2

这里其实可以把事件 Event 当作是产品,而 Publisher 是生产者, Listener 是消费者。发布/订阅模式的好处在于生产者消费者之间可以解耦,并不会产生阻塞(我有产品自然会通知你,你不用过来问我有没有)。

也就是说上面代码中发布者调用applicationEventPublisher.publishEvent(msg); 是会将事件发送给了EventMultiCaster, 而后由EventMultiCaster注册着所有的Listener,然后根据事件类型决定转发给那个Listener。

来自 Spring 事件机制

Spring 定义的事件 Event

ApplicationEvent是Spring事件的顶层抽象类,代表事件本身,继承自JDK的EventObject。Spring提供了一些内置事件,如ContextClosedEvent、ContextStartedEvent、ContextRefreshedEvent、ContextStopedEvent等

  • ContextStartedEvent:ApplicationContext启动后触发的事件;(目前版本没有任何作用)
  • ContextStoppedEvent:ApplicationContext停止后触发的事件;(目前版本没有任何作用)
  • ContextRefreshedEvent:ApplicationContext初始化或刷新完成后触发的事件;(容器初始化完成后调用)
  • ContextClosedEvent:ApplicationContext关闭后触发的事件;(如web容器关闭时自动会触发spring容器的关闭,如果是普通java应用,需要调用ctx.registerShutdownHook();注册虚拟机关闭时的钩子才行)

注:org.springframework.context.support.AbstractApplicationContext抽象类实现了LifeCycle的start和stop回调并发布ContextStartedEvent和ContextStoppedEvent事件;但是无任何实现调用它,所以目前无任何作用。

public abstract class ApplicationEvent extends EventObject {
    private static final long serialVersionUID = 7099057708183571937L;
    private final long timestamp = System.currentTimeMillis();

    public ApplicationEvent(Object source) {
        super(source);
    }

    public final long getTimestamp() {
        return this.timestamp;
    }
}

事件类型

  • 发布的事件类型是ApplicationEvent的实现类A
    那么所有监听者的onApplicationEvent的参数类型是A或者A的子类都会收到事件。
  • 发布的事件类型是不是ApplicationEvent类型,类型是Object B.
    这种情况下,最终事件会被包装成PayloadApplicationEvent<B>, 那么所有监听者方法onApplicationEvent的参数是PayloadApplicationEvent<B>的监听者会收到, 假设有C是B的父类,且有一个监听者X监听PayloadApplicationEvent<C>,那X是收不到PayloadApplicationEvent<B>类型的事件的

监听器 Listener

ApplicationListener是Spring事件监听器顶层接口,所有的监听器都实现该接口,继承自 JDK的 EventListener。Spring提供了一些易扩展的接口,如SmartApplicationListener、GenericApplicationListener

public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {  
    void onApplicationEvent(E event);  
}

其只提供了 onApplicationEvent方法,我们需要在该方法实现内部判断事件类型来处理,也没有提供按顺序触发监听器的语义,所以Spring提供了另一个接口,SmartApplicationListener:

public interface SmartApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered {  
        //如果实现支持该事件类型 那么返回true  
    boolean supportsEventType(Class<? extends ApplicationEvent> eventType);  

        //如果实现支持“目标”类型,那么返回true  
    boolean supportsSourceType(Class<?> sourceType);  

        //顺序,即监听器执行的顺序,值越小优先级越高  
        int getOrder();  
}

该接口可方便实现去判断支持的事件类型、目标类型,及执行顺序。

举例:定义有序监听器

实现SmartApplicationListener接口即可。来自 Spring提供的事件驱动模型/观察者抽象

package com.sishuok.hello;  
import org.springframework.context.ApplicationEvent;  
public class ContentEvent extends ApplicationEvent {  
    public ContentEvent(final String content) {  
        super(content);  
    }  
} 
// super(content) from ApplicationEvent
public ApplicationEvent(Object source) {
    super(source);
    this.timestamp = System.currentTimeMillis();
}
// super(content) from EventObject
public EventObject(Object source) {
    if (source == null)
        throw new IllegalArgumentException("null source");

    this.source = source;
}

public Object getSource() {
    return source;
}

所以可以使用 new ContentEvent(‘…’).getSource()来获取 content.

package com.sishuok.hello;  
import org.springframework.context.ApplicationEvent;  
import org.springframework.context.event.SmartApplicationListener;  
import org.springframework.stereotype.Component;  

@Component  
public class WangwuListener implements SmartApplicationListener {  

   @Override  
   public boolean supportsEventType(final Class<? extends ApplicationEvent> eventType) {  
       return eventType == ContentEvent.class;  
   }  
   @Override  
   public boolean supportsSourceType(final Class<?> sourceType) {  
       return sourceType == String.class;  
   }  
   @Override  
   public void onApplicationEvent(final ContentEvent event) {  
       System.out.println("王五在孙六之前收到新的内容:" + event.getSource());  
   }  
   @Override  
   public int getOrder() {  
       return 1;  
   }  
}
package com.sishuok.hello;  
import org.springframework.context.ApplicationEvent;  
import org.springframework.context.event.SmartApplicationListener;  
import org.springframework.stereotype.Component;  

@Component  
public class SunliuListener implements SmartApplicationListener {  

    @Override  
    public boolean supportsEventType(final Class<? extends ApplicationEvent> eventType) {  
        return eventType == ContentEvent.class;  
    }  

    @Override  
    public boolean supportsSourceType(final Class<?> sourceType) {  
        return sourceType == String.class;  
    }  

    @Override  
    public void onApplicationEvent(final ContentEvent event) {  // 这里也可以写 ApplicationEvent event
        System.out.println("孙六在王五之后收到新的内容:" + event.getSource());  
    }  

    @Override  
    public int getOrder() {  
        return 2;  
    }  
}
  • supportsEventType:用于指定支持的事件类型,只有支持的才调用onApplicationEvent;
  • supportsSourceType:支持的目标类型,只有支持的才调用onApplicationEvent;
  • getOrder:即顺序,越小优先级越高

一旦 ContentEvent 被 ApplicationEvetnPublisher 发布出去后,就会轮到MultiCaster 来工作,它会根据EventType 来匹配对应的Listener。

发布事件者 Publisher

ApplicationEventPublisher是Spring的事件发布接口,事件源通过该接口的publishEvent方法发布事件,所有的应用上下文 applicationContext 都具备事件发布能力,因为ApplicationContext继承了该接口

public interface ApplicationEventPublisher {

    void publishEvent(ApplicationEvent var1);

    void publishEvent(Object var1);
}
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
    String getId();

    String getApplicationName();

    String getDisplayName();

    long getStartupDate();

    ApplicationContext getParent();

    AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}
// in class AbstractApplicationContext
// 因为 ApplicationContext 同时也是一个 ApplicationEventPublisher, 所以也实现了 publishEvent 的方法
// 这里传进来的 eventType 是 null类型
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
    Assert.notNull(event, "Event must not be null");

    // Decorate event as an ApplicationEvent if necessary
    ApplicationEvent applicationEvent;
    if (event instanceof ApplicationEvent) {
        applicationEvent = (ApplicationEvent) event;
    }
    else {
        // 如果不是 ApplicationEvent类型,就会被包装成 PayloadApplicationEvent类
        applicationEvent = new PayloadApplicationEvent<>(this, event);
        if (eventType == null) {
            eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
        }
    }

    // Multicast right now if possible - or lazily once the multicaster is initialized
    if (this.earlyApplicationEvents != null) {
        this.earlyApplicationEvents.add(applicationEvent);
    }
    else {
        // 委派给 事件多播器 applicationEventMulticaster 来执行 multicastEvent 方法
        // 很明显传入了一个 Event 和其对应的 EventType 以此来找到一个或多个匹配的 Listener
        // 注意如果这里的 event 是 ApplicationEvent 类型,那么 eventType 为 null
        // 如果是 PayloadApplicationEvent 类型,则不为 null
        getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
    }

    // Publish event via parent context as well...
    if (this.parent != null) {
        if (this.parent instanceof AbstractApplicationContext) {
            ((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
        }
        else {
            this.parent.publishEvent(event);
        }
    }
}

事件多播器 ApplicationEventMulticaster

ApplicationEventMulticaster 是Spring事件机制中的事件广播器,它默认提供一个SimpleApplicationEventMulticaster 实现,如果用户没有自定义广播器,则使用默认的(初始化逻辑见AbstractApplicationContext 的 refresh 方法)。它通过父类 AbstractApplicationEventMulticaster 的getApplicationListeners 方法从事件注册表中获取事件监听器 Listener,并且通过 invokeListener 方法执行监听器的具体逻辑。

public interface ApplicationEventMulticaster {
    void addApplicationListener(ApplicationListener<?> var1);

    void addApplicationListenerBean(String var1);

    void removeApplicationListener(ApplicationListener<?> var1);

    void removeApplicationListenerBean(String var1);

    void removeAllListeners();

    void multicastEvent(ApplicationEvent var1);

    void multicastEvent(ApplicationEvent var1, ResolvableType var2);
}
// 在 AbstractApplicationContext 的 refresh() 方法里面

// 初始化应用消息广播器,并放入“applicationEventMulticaster” bean中
initApplicationEventMulticaster();

// 
protected void initApplicationEventMulticaster() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    // 查找beanFactory 里面是否有 名称为”applicationEventMulticaster“的bean
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isTraceEnabled()) {
            logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    else {
        // 如果 beanFactory 里面没有名称为”applicationEventMulticaster“的bean
        // 那么新建一个SimpleApplicationEventMulticaster的bean,并注册到 beanFactory 中
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
                         "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
        }
    }
}

使用 multicastEvent 方法把事件发送到对应的 Listener 中,然后执行 invokeListener, 接着Listener 才会最终调用 onApplicationEvent 方法。注意:这里其实并不是真的把事件发送到 Listeners,而是 multicaters广播器本身会把这些listener保存下来(一开始是空的,要去容器里获取,获取后就保存到本地的缓存中),然后在本地缓存中根据 EventType 一个个匹配这些 Listeners。

public void multicastEvent(ApplicationEvent event) {
    this.multicastEvent(event, this.resolveDefaultEventType(event));
}

public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
    ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
    // 这个getApplicationListeners() 的分析较为复杂
    Iterator var4 = this.getApplicationListeners(event, type).iterator();

    while(var4.hasNext()) {
        final ApplicationListener<?> listener = (ApplicationListener)var4.next();
        Executor executor = this.getTaskExecutor();
        if (executor != null) {
            //发现如果 SimpleApplicationEventMulticaster对象的线程池属性 Executor taskExecutor不为null则异步执行监听方法
            executor.execute(new Runnable() {
                public void run() {
                    // 通过 invokeListener 方法执行监听器的具体逻辑。
                    SimpleApplicationEventMulticaster.this.invokeListener(listener, event);
                }
            });
        } else {
            this.invokeListener(listener, event);
        }
    }

}

// In SimpleApplicationEventMulticaster clas
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
    ErrorHandler errorHandler = this.getErrorHandler();
    if (errorHandler != null) {
        try {
            // 看到 doInvokeListener 就知道要真正调用了
            this.doInvokeListener(listener, event);
        } catch (Throwable var5) {
            errorHandler.handleError(var5);
        }
    } else {
        // 看到 doInvokeListener 就知道要真正调用了
        this.doInvokeListener(listener, event);
    }
}

private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
    try {
        // 这就是我们在自定义的 Listener 中定义的 onApplicationEvent() 方法了
        listener.onApplicationEvent(event);
    } catch (ClassCastException var6) {
        String msg = var6.getMessage();
        if (msg != null && !msg.startsWith(event.getClass().getName())) {
            throw var6;
        }

        Log logger = LogFactory.getLog(this.getClass());
        if (logger.isDebugEnabled()) {
            logger.debug("Non-matching event type for listener: " + listener, var6);
        }
    }
}

默认的广播器是同步调用监听器的执行逻辑,但是可以通过为广播器配置Executor实现监听器的异步执行。

在Spring中通常是ApplicationContext本身担任监听器注册表的角色,在其子类AbstractApplicationContext中就聚合了事件广播器 ApplicationEventMulticaster 和事件监听器 ApplicationListnener,并且提供注册监听器的 addApplicationListnener方法。而且别忘了,AbstractApplicationContext(ApplicationContext)本身就是一个ApplicationEventPublisher(实现了该接口),所以可以直接使用 context.publishEvent(..)来发布事件。

// In class AbstractApplicationContext

/** Helper class used in event publishing. */
@Nullable
private ApplicationEventMulticaster applicationEventMulticaster;

/** Statically specified listeners. */
// 内部使用一个 Set 来存放 applicationListeners
private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();

/** Local listeners registered before refresh. */
@Nullable
private Set<ApplicationListener<?>> earlyApplicationListeners;

/** ApplicationEvents published before the multicaster setup. */
@Nullable
private Set<ApplicationEvent> earlyApplicationEvents;

/**
 * Return the list of statically specified ApplicationListeners.
 */
// 调用 getApplicationListeners() 方法来返回 applicationListeners
public Collection<ApplicationListener<?>> getApplicationListeners() {
    return this.applicationListeners;
}

// 添加事件监听器
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
    Assert.notNull(listener, "ApplicationListener must not be null");
    if (this.applicationEventMulticaster != null) {
        this.applicationEventMulticaster.addApplicationListener(listener);
    }
    this.applicationListeners.add(listener);
}

当一个事件源产生事件(这里通常由我们的业务来决定)时,它通过事件发布器 ApplicationEventPublisher 发布事件,然后事件广播器 ApplicationEventMulticaster 会去事件注册表 ApplicationContext(Listener也是bena,也需要在容器中实例化) 中找到事件监听器 ApplicationListnener,并且逐个执行监听器的 onApplicationEvent方法,从而完成事件监听器的逻辑。

SpringBoot 事件-监听机制

SpringApplicationEvent是SpringBoot事件的顶层抽象类,且SpringBoot内置了7个事件:

Spring的事件监听(Event-Listener)机制 - 图3

  • ApplicationStartingEvent:SpringBoot启动开始的时候发布的事件(starting 阶段)
  • ApplicationEnvironmentPreparedEvent:SpringBoot对应Environment准备完毕时发布的事件,此时上下文还没有创建,该事件中可以获取配置信息。通过监听该事件可以修改默认的配置信息,配置中心就是借助该事件完成将远端配置放入应用中(environment prepared 阶段)
  • ApplicationContextInitializedEvent:当准备好上下文,并且在加载任何Bean之前发布的事件。该事件可以获取上下文信息(context prepared 阶段)
  • ApplicationPreparedEvent:上下文创建完成时发布的事件,此时的Bean还没有完全加载完成,只是加载了部分特定Bean。该事件可以获取上下文信息,但是无法获取自定义Bean,因为还没有被加载
    (context loaded 阶段)
  • ApplicationStartedEvent:上下文刷新(完成所有Bean的加载)之后,但是还没有调用任何ApplicationRunner 和 CommandLineRunner 运行程序之前发布的事件。该事件同样可以获取上下文信息,并且可以获取自定义的Bean(started 阶段)
  • ApplicationReadyEvent:完成 ApplicationRunner 和 CommandLineRunner 运行程序调用之后发布的事件,此时的SpringBoot已全部启动完成。该事件同样可以获取上下文信息(running 阶段)
  • ApplicationFailedEvent:SpringBoot启动异常时发布的事件。该事件可以获取上下文信息和异常信息,通过该事件可以友好地完成资源的回收(fail)

上述7个事件在容器启动的合适阶段进行发布,发布顺序自上而下,可查看SpringApplication的run(String… args)方法,分别对应 SpringApplicationRunListener 的7个方法,源码如下:

// 该接口规定了SpringBoot的生命周期,会在各个生命周期广播响应的事件,调用实际的监听器
public interface SpringApplicationRunListener {
    // 发布ApplicationStartingEvent
    default void starting() {
    }
    // 发布ApplicationEnvironmentPreparedEvent
    default void environmentPrepared(ConfigurableEnvironment environment) {
    }
    // 发布ApplicationContextInitializedEvent
    default void contextPrepared(ConfigurableApplicationContext context) {
    }
    // 发布ApplicationPreparedEvent
    default void contextLoaded(ConfigurableApplicationContext context) {
    }
    // 发布ApplicationStartedEvent
    default void started(ConfigurableApplicationContext context) {
    }
    // 发布ApplicationReadyEvent
    default void running(ConfigurableApplicationContext context) {
    }
    // 发布ApplicationFailedEvent
    default void failed(ConfigurableApplicationContext context, Throwable exception) {
    }
}

上述接口提供了唯一的实现类 EventPublishingRunListener,该类聚合了 SpringApplication 和SimpleApplicationEventMulticaster,前4个事件的发布由广播器完成,后3个委托ApplicationContext完成发布,其实最终都是由广播器负责发布。

如果我们想要实现对于spring-boot整个生命周期各个状态变化进行监听,然后执行相应的业务代码,只需要让自定义 Listener 类实现 SpringApplicationRunListener 接口即可。来自 Spring Boot的Listener机制的用法和实现原理详解

Spring的事件监听(Event-Listener)机制 - 图4

Spring的事件监听(Event-Listener)机制 - 图5

运行结果:

Spring的事件监听(Event-Listener)机制 - 图6

从运行结果我们可以看出:

  • 各个状态回调的顺序为:starting->environmentPrepared->contextPrepared->contextLoaded->started->running,再加上一个启动出错时的回调failed
  • 每一个状态的回调对应的是spring-boot程序在启动时的不同的阶段,可以利用的spring-boot资源也是不一样的,比如starting状态就无法利用任何spring-boot相关的功能,因为这个时候spring-boot还没有进行任何实际的初始化。

注意:这个 SpringApplicationRunListener 不和其它的 Listeners 一样,里面没有onApplicationEvent方法,它是Springboot的 SpringApplication.run 方法附带的产物,因为执行run方法时,会去resources目录下的spring.factories查找键为org.springframework.context.SpringApplicationRunListener 的value(实现类的全类名),然后创建了这些类后,会在接下来执行run方法中调用这些实现类的方法。点进去方法可以看到其实这个”Listener”也是用广播器发送给对应的 Listener执行。

监听器使用方式

来自 Spring事件监听机制

1、通过SPI机制配置

在resources目录下新建META-INF目录,并创建名为spring.factories的文件,在文件中声明以ApplicationListener接口全路径为键的配置,配置内容为ApplicationListener实现类的全路径,若有多个以逗号间隔,示例如下:

org.springframework.context.ApplicationListener=\
com.lyentech.bdc.tuya.listener.HunterApplicationContextInitializedListener,\
com.lyentech.bdc.tuya.listener.HunterApplicationEnvironmentPreparedListener,\
com.lyentech.bdc.tuya.listener.HunterApplicationFailedListener,\
com.lyentech.bdc.tuya.listener.HunterApplicationPreparedListener,\
com.lyentech.bdc.tuya.listener.HunterApplicationReadyListener,\
com.lyentech.bdc.tuya.listener.HunterApplicationStartedListener,\
com.lyentech.bdc.tuya.listener.HunterApplicationStartingListener

Spring在启动的时候会加载 spring.factories 中配置的监听器实现类,并在合适的阶段通过发布事件触发相应监听器的逻辑。此方式可以实现针对任何事件(SpringBoot内置7个事件都支持)监听器的成功加载。

2、启动类main方法手动添加

在引用启动类的main方法中先创建一个SpringApplication实例,然后调用addListeners方法添加自定义的监听器实现类,最后调用实例的run方法启动容器,示例如下:

public class TuyaServiceApplication{
    public static void main(String[] args) {
        // 习惯写法
        //SpringApplication.run(TuyaServiceApplication.class, args);

        // 新写法:实例化对象、添加监听器、启动
        SpringApplication springApplication = new SpringApplication(TuyaServiceApplication.class);
        springApplication.addListeners(new HunterApplicationStartingListener());
        springApplication.addListeners(new HunterApplicationPreparedListener());
        springApplication.run(args);
    }
}

这种方式也可以实现针对任何事件(SpringBoot内置7个事件都支持)监听器的成功加载。

3、使用@Component

在监听器实现类定义的时候适用@Component注解注释当前监听器,确保让Spring可以扫描到并完成加载,示例如下:

// 监听ApplicationReadyEvent事件
@Component
public class HunterApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        System.err.println("===execute 【ApplicationReadyEvent】 listener...");
    }
}

这种方式只能实现对 SpringBoot 内置事件的**后3个**进行监听,因为容器启动在借助@Component加载Bean的时候,前4个事件已经发布了,所以不会生效。

4、使用@Component和@EventListener

这种方式可以减少监听器类的个数,示例如下:

@Component
public class HunterListener {

    @EventListener
    public void listener1(ApplicationStartingEvent event){
        System.err.println("使用@EventListener注册监听器,监听ApplicationStartingEvent事件");
    }

    @EventListener
    public void listener2(ApplicationStartedEvent event){
        System.err.println("使用@EventListener注册监听器,监听ApplicationStartedEvent事件");
    }

    @EventListener
    public void listener3(ApplicationReadyEvent event){
        System.err.println("使用@EventListener注册监听器,监听ApplicationReadyEvent事件");
    }
}

这种方式配置的对前四个事件的监听不会生效,原因同第三种方式。

5、总结

前三种方式的监听器都需要通过实现 ApplicationListener 接口给出具体定义,如果监听器特别多,就会造成类的数量很大;第四种方式仅需一个类就可以完成多个监听器的定义,但是适用的事件有限。

如果多种方式共存,监听器会被执行多次。

如果需要指定同类事件监听器的执行顺序,可以通过==@Order 或者实现Ordered接口==完成。

监听器默认同步执行,如果需要异步执行,一种方式是为广播器 multicaster 提供Executor,另一种就是在后两种使用方式上结合@Async 注解(此时需要通过@EnableAsync 开启容器对异步的支持)。