上一篇: 13-Spring源码解析之refresh(6)——【initMessageSource】和【initApplicationEventMulticaster】
上一篇,我们讲解了refresh
方法的第7个initMessageSource
和第8个initApplicationEventMulticaster
方法。接着本篇文章讲解refresh
方法中调用的第9个onRefresh
方法和第10个registerListeners
方法。
一、onRefresh
方法
这个方法是一个空方法,留给子类去实现。在容器刷新的时候可以自定义逻辑
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
本项目没有重写这个方法,因此在此先不做详细分析。若以后遇到例子再进行详细补充。
二、registerListeners
方法
protected void registerListeners() {
// Register statically specified listeners first.
// 首先获取beanFactory中的ApplicationListeners。
// 因为我们没有设置ApplicationListeners,所以此处不会执行for循环中的内容
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 获取beanFactory中所有ApplicationListener类型的beanName
// 当前项目中还没有ApplicationListener类型的bean
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...
// 如果我们有早期应用事件,这里就直接发布,同时把earlyApplicationEvents设置为null
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
这两个方法比较简单,所以不需要详细介绍了。若以后有详细的例子,还会补充的~
下一篇,我们就来到了重头戏,看refresh
方法是如何通过finishBeanFactoryInitialization
来初始化剩下的所有非懒加载的Bean
的吧。