spring ApplicationListener源码解析

517 阅读1分钟

ApplicationListener和ApplicationEvent使用观察者模式

  • 时序图

其中publishEvent方法注册事件,invokeListener方法为触发事件,具体的事件处理函数由实现了ApplicationListener的onApplicationEvent方法处理,ApplicationEvent是onApplicationEvent的传入参数,也就是事件源对象。

  • 源码分析

    1. multicastEvent解析

      public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
      	ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
      	// getApplicationListeners 获取IOC注入时所有实现ApplicationLIsteners列表
      	for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
      	//如果有任务处理器注入,利用任务队列进行异步处理事件
      		Executor executor = getTaskExecutor();
      		if (executor != null) {
      			executor.execute(new Runnable() {
      				@Override
      				public void run() {
      				// 触发事件
      					invokeListener(listener, event);
      				}
      			});
      		}
      		else {
      			invokeListener(listener, event);
      		}
          }
      }
      
    2. invokeListener解析

       protected void invokeListener(ApplicationListener listener, ApplicationEvent event) {
          ... 一些错误处理省略
          // 最终调用实际事件处理方法
          listener.onApplicationEvent(event);
          ... 省略
       }
      
      
      
  • github demo