registerListeners() 这人个方法作用:检查监听器的bean 之后向容器中注册
// 首先注册静态指定的侦听器。 手动放入的 listener
for (ApplicationListener<?> listener : getApplicationListeners()) {
// 将监听器 放入多播事件中
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 从容器中获取所有实现了ApplicationListener接口的bd的bdName
// 放入applicationListenerBeans
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 这里先发布早期的监听器. (earlyEventsToProcess )在广播设置之前发布的ApplicationEvent
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
// 执行
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
这里有一个不好理解的点 earlyEventsToProcess
earlyApplicationEvents用来存放容器启动后需要发布的事件。它会在容器启动的prepareRefresh环节初始化为一个LinkedHashSet。(如果对spring的初始化流程不熟悉,请参考附录中的内容)
他是在 prepareRefresh 环节被创建 , 在 registerListeners 结束后被调用 并且会被清空 , 也就是我我们可以在容器初始化过程中 添加想要在 registerListeners 执行之后 监听器 , 并且只执行一次, 那他到底有什么左右呢 ? 查了很多资料也没有找到,我想的是 如果需要我们自定义实现容易时 那么也就可以在这里添加事件去执行了 害!! 有懂得大佬欢迎指教
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// 将本地应用程序侦听器重置为预刷新状态.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 创建多播list
this.earlyApplicationEvents = new LinkedHashSet<>();