registerListeners 是将各种实现了 ApplicationListener 的监听器注册到 ApplicationEventMulticaster 事件广播器中
AbstractApplicationContext -> registerListeners
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
// Register statically specified listeners first.
/**
* 首先判断之前在 prepareRefresh 这个方法中是否有向 earlyApplicationListeners 这个集合中加入监听器
* 如果有则加入到 广播器的监听器集合中
* */
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!
/**
* 再判断在当前工厂中是否有bean是 ApplicationListener的实现类
* 如果有则实例化并加入到
* */
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> earlyApplicationEvents 这个集合中的事件
* 我的理解是如果你有事件需要提前发布就把它加入到 earlyApplicationEvents 这个集合中,那么这里就会被发布掉
* 否则就会在 finishRefresh这个方法中 中才会发布且发布的是 ContextRefreshedEvent 这个事件
* */
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}