14-Spring源碼解析之refresh(7)——【onRefresh】和【registerListeners】

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章