上一篇: 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
的吧。