备战面试日记(4.2.12)- (框架.Spring【十二】之Spring IOC 源码registerListeners())
本人本科毕业,21届毕业生,一年工作经验,简历专业技能如下,现根据简历,并根据所学知识复习准备面试。
记录日期:2022.1.4
大部分知识点只做大致介绍,具体内容根据推荐博文链接进行详细复习。
文章目录
框架原理 - Spring(十二)之Spring IOC 源码registerListeners()
AbstractApplicationContext#registerListeners()
注册***。
protected void registerListeners() {
// 【翻译注释】首先注册静态指定的侦听器
/** * getApplicationListeners就是获取applicationListeners * 是通过applicationListeners(listener)添加的 * 放入applicationListeners中 */
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 【翻译注释】不要在这里初始化FactoryBeans:我们需要让所有常规bean保持未初始化状态,以便让后处理器应用于它们
/** * 从容器中获取所有实现了ApplicationListener接口的bean的beanName * 放入applicationListenerBeans * */
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 【翻译注释】发布早期应用程序事件现在我们终于有了一个多主机。。。
/** * 这里先发布早期的*** */
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
getApplicationEventMulticaster().addApplicationListener(listener)
getApplicationEventMulticaster()方法实现如下:
即获取我们前面初始化好的广播器。
/** Helper class used in event publishing. */
@Nullable
private ApplicationEventMulticaster applicationEventMulticaster;
ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
if (this.applicationEventMulticaster == null) {
throw new IllegalStateException("ApplicationEventMulticaster not initialized - " +
"call 'refresh' before multicasting events via the context: " + this);
}
return this.applicationEventMulticaster;
}
addApplicationListener(listener)方法实现如下:
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
synchronized (this.defaultRetriever) {
// 【翻译注释】显式删除代理的目标(如果已注册),以避免重复调用同一侦听器
Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
if (singletonTarget instanceof ApplicationListener) {
this.defaultRetriever.applicationListeners.remove(singletonTarget);
}
this.defaultRetriever.applicationListeners.add(listener);
this.retrieverCache.clear();
}
}
发布早期的***
this.earlyApplicationEvents默认为空。


