Spring容器之注册事件监听器

143 阅读1分钟

registerListeners()

源码分析

/**
   * Add beans that implement ApplicationListener as listeners.
   * Doesn't affect other listeners, which can be added without being beans.
   */
  protected void registerListeners() {
  	// 1、 向事件广播器注册静态指定的事件监听器
      // Register statically specified listeners first.
      for (ApplicationListener<?> listener : getApplicationListeners()) {
          getApplicationEventMulticaster().addApplicationListener(listener);
      }

	// 2、向事件广播器注册未实例化的事件监听器
      // Do not initialize FactoryBeans here: We need to leave all regular beans
      // uninitialized to let post-processors apply to them!
      String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
      for (String listenerBeanName : listenerBeanNames) {
          getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
      }

	// 3、广播早期事件
      // 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);
          }
      }
  }