Spring的ApplicationEventMulticaster

Spring的观察者模式

Spring的观察者模式
  • 事件源:事件的发布者
  • 事件:消息
  • 监听器:事件的订阅者,一个监听器只监听一个事件基类及其子类
  • 多播器:事件源向多播器发送事件,多播器遍历其持有的监听器,匹配监听该事件类型的监听器,并执行监听器的方法。

执行流程

Spring多播器执行流程

源码分析

接口定义

ApplicationListener

// 这里的泛型E指该监听器要监听的事件类型
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

   /**
    * Handle an application event.
    * @param event the event to respond to
    */
   // 事件回调逻辑
   void onApplicationEvent(E event);

}

ApplicationEventMulticaster

public interface ApplicationEventMulticaster {

   /**
    * Add a listener to be notified of all events.
    * @param listener the listener to add
    */
   // 根据listener对象注册listener
   void addApplicationListener(ApplicationListener<?> listener);

   /**
    * Add a listener bean to be notified of all events.
    * @param listenerBeanName the name of the listener bean to add
    */
   // 根据listener的BeanName注册listener
   void addApplicationListenerBean(String listenerBeanName);

   /**
    * Remove a listener from the notification list.
    * @param listener the listener to remove
    */
   // 根据listener对象移除listener
   void removeApplicationListener(ApplicationListener<?> listener);

   /**
    * Remove a listener bean from the notification list.
    * @param listenerBeanName the name of the listener bean to add
    */
   // 根据listener的BeanName移除listener
   void removeApplicationListenerBean(String listenerBeanName);

   /**
    * Remove all listeners registered with this multicaster.
    * <p>After a remove call, the multicaster will perform no action
    * on event notification until new listeners are being registered.
    */
   // 移除所有的listener
   void removeAllListeners();

   /**
    * Multicast the given application event to appropriate listeners.
    * <p>Consider using {@link #multicastEvent(ApplicationEvent, ResolvableType)}
    * if possible as it provides a better support for generics-based events.
    * @param event the event to multicast
    */
   // 广播消息
   void multicastEvent(ApplicationEvent event);

   /**
    * Multicast the given application event to appropriate listeners.
    * <p>If the {@code eventType} is {@code null}, a default type is built
    * based on the {@code event} instance.
    * @param event the event to multicast
    * @param eventType the type of event (can be null)
    * @since 4.2
    */
   // 广播特定类型的消息
   void multicastEvent(ApplicationEvent event, ResolvableType eventType);

}

EventObject

public class EventObject implements java.io.Serializable {

    private static final long serialVersionUID = 5516075349620653480L;

    /**
     * The object on which the Event initially occurred.
     */
    // 事件源
    protected transient Object source;

    /**
     * Constructs a prototypical Event.
     *
     * @param    source    The object on which the Event initially occurred.
     * @exception  IllegalArgumentException  if source is null.
     */
    public EventObject(Object source) {
        if (source == null)
            throw new IllegalArgumentException("null source");

        this.source = source;
    }

    /**
     * The object on which the Event initially occurred.
     *
     * @return   The object on which the Event initially occurred.
     */
    public Object getSource() {
        return source;
    }

    /**
     * Returns a String representation of this EventObject.
     *
     * @return  A a String representation of this EventObject.
     */
    public String toString() {
        return getClass().getName() + "[source=" + source + "]";
    }
}

执行流程

initApplicationEventMulticaster

// 初始化多播器
protected void initApplicationEventMulticaster() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   // 如果BeanFactory中存在用户自定义的多播器,则使用它
   if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
      this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
      if (logger.isDebugEnabled()) {
         logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
      }
   }
   // 否则,使用Spring默认的多播器
   else {
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
      if (logger.isDebugEnabled()) {
         logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
               APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
               "': using default [" + this.applicationEventMulticaster + "]");
      }
   }
}

registerListeners

protected void registerListeners() {
   // Register statically specified listeners first.
   // 注册BeanFactory中的listener
for (ApplicationListener<?> listener : getApplicationListeners()) {
      getApplicationEventMulticaster().addApplicationListener(listener);
   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let post-processors apply to them!
   // 注册BeanDefinition中的listener
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
   for (String listenerBeanName : listenerBeanNames) {
      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
   }

   // Publish early application events now that we finally have a multicaster...
   // 发布早期发布的事件到多播器
   Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
   this.earlyApplicationEvents = null;
   if (earlyEventsToProcess != null) {
      for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
         getApplicationEventMulticaster().multicastEvent(earlyEvent);
      }
   }
}
private class ListenerRetriever {

   // 监听器对象(BeanFactory中的listener)
   public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<ApplicationListener<?>>();

   // 监听器的BeanName(BeanDefinition中的listener)
   public final Set<String> applicationListenerBeans = new LinkedHashSet<String>();

   private final boolean preFiltered;

   public ListenerRetriever(boolean preFiltered) {
      this.preFiltered = preFiltered;
   }

   // 获取所有的listener
   public Collection<ApplicationListener<?>> getApplicationListeners() {
      List<ApplicationListener<?>> allListeners = new ArrayList<ApplicationListener<?>>(
            this.applicationListeners.size() + this.applicationListenerBeans.size());
      // 获取applicationListeners
      allListeners.addAll(this.applicationListeners);
      // 获取applicationListenerBeans
      if (!this.applicationListenerBeans.isEmpty()) {
         BeanFactory beanFactory = getBeanFactory();
         for (String listenerBeanName : this.applicationListenerBeans) {
            try {
               ApplicationListener<?> listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class);
               if (this.preFiltered || !allListeners.contains(listener)) {
                  allListeners.add(listener);
               }
            }
            catch (NoSuchBeanDefinitionException ex) {
               // Singleton listener instance (without backing bean definition) disappeared -
               // probably in the middle of the destruction phase
}
         }
      }
      AnnotationAwareOrderComparator.sort(allListeners);
      return allListeners;
   }
}

multicastEvent

public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
   ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
   // 根据Type匹配listener
   for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
      // 异步事件会用到executor
      Executor executor = getTaskExecutor();
      // 遍历匹配type的listener,执行回调方法
      if (executor != null) {
         executor.execute(new Runnable() {
            @Override
            public void run() {
               invokeListener(listener, event);
            }
         });
      }
      // 同步事件的executor为null
      else {
         invokeListener(listener, event);
      }
   }
}
上一篇
下一篇