Spring源碼學習-IOC初始化過程-refresh()方法揭祕

前面兩篇分別講了Spring初始化容器的時候XML配置方式和註解方式如何解析註冊BeanDefinition的整個過程。Spring在初始化 ApplicationContext容器的過程當中註冊BeanDefinition只是其中的一個步驟,其中還有不少處理好比初始化國際化資源、應用事件廣播、應用事件監聽等都是在抽象類AbstractApplicationContext的refresh()方法中完成的。java

下面是整個refresh()方法的流程 app

1.prepareRefresh():容器刷新前的準備,設置了開始時間、狀態、驗證全部標記爲必需的屬性是否可解析和一個模板方法initPropertySources()。post

2.obtainFreshBeanFactory():裏面兩個模板方法refreshBeanFactory()和getBeanFactory()。看過以前xml配置方式註冊BeanDefinition的應該知道入口就是AbstractRefreshableApplicationContext的refreshBeanFactory()。getBeanFactory()返回子類建立的bean factory實例,AbstractApplicationContext中不存在BeanFactory的實例,因此提供模板方法由子類具體建立提供。spa

3.prepareBeanFactory(beanFactory):容器使用前對bean工廠進行一些處理屬性設置。rest

4.postProcessBeanFactory(beanFactory):模板方法提供給子類對bean工廠進行一些處理。code

5.invokeBeanFactoryPostProcessors(beanFactory):這是一個重點,也是一個擴展點,同時用java作配置時的掃描註冊BeanDefinition的入口也在這裏。cdn

首先初始化類型爲BeanDefinitionRegistryPostProcessors而且實現了接口PriorityOrdered(高優先級)的bean並執行postProcessBeanDefinitionRegistry方法,ConfigurationClassPostProcessor就是在這裏執行而後調用doscan方法掃描註冊bean定義。xml

// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let the bean factory post-processors apply to them!
	// Separate between BeanDefinitionRegistryPostProcessors that implement
	// PriorityOrdered, Ordered, and the rest.
	List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

	// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
	String[] postProcessorNames =
			beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
	for (String ppName : postProcessorNames) {
		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
			processedBeans.add(ppName);
		}
	}
	sortPostProcessors(currentRegistryProcessors, beanFactory);
	registryProcessors.addAll(currentRegistryProcessors);
	invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
	currentRegistryProcessors.clear();
複製代碼

而後就是實例化實現了Ordered(排序接口)的BeanDefinitionRegistryPostProcessors實例並調用postProcessBeanDefinitionRegistry方法blog

// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
	if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
		currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
		processedBeans.add(ppName);
	}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
複製代碼

最後實例化沒有實現排序接口的BeanDefinitionRegistryPostProcessors實例並調用postProcessBeanDefinitionRegistry方法。 後面是實例實例化實現了BeanFactoryPostProcessor接口的bean並調用postProcessBeanFactory方法,調用順序和BeanDefinitionRegistryPostProcessors同樣。排序

在這裏咱們能夠插入本身的實現,經過實現BeanDefinitionRegistryPostProcessors接口對bean定義作一些處理,實現BeanFactoryPostProcessor接口能夠對bean工廠作一些處理工做。

6.registerBeanPostProcessors(beanFactory):這也是一個擴展點,在這裏會提早初始化全部實現了BeanPostProcessor接口的bean,但不會執行裏面的方法。BeanPostProcessor 實例 在getBean()以前和以後能夠作一些處理,AOP就是基於BeanPostProcessor實現的。 下面是源碼實現

public static void registerBeanPostProcessors(
	ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

	// Register BeanPostProcessorChecker that logs an info message when
	// a bean is created during BeanPostProcessor instantiation, i.e. when
	// a bean is not eligible for getting processed by all BeanPostProcessors.
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// Separate between BeanPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
	List<String> orderedPostProcessorNames = new ArrayList<>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
	for (String ppName : postProcessorNames) {
		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			priorityOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// First, register the BeanPostProcessors that implement PriorityOrdered.
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

	// Next, register the BeanPostProcessors that implement Ordered.
	List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
	for (String ppName : orderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		orderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, orderedPostProcessors);

	// Now, register all regular BeanPostProcessors.
	List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	for (String ppName : nonOrderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		nonOrderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

	// Finally, re-register all internal BeanPostProcessors.
	sortPostProcessors(internalPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, internalPostProcessors);

	// Re-register post-processor for detecting inner beans as ApplicationListeners,
	// moving it to the end of the processor chain (for picking up proxies etc).
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	    
}
複製代碼

處理邏輯跟上面的BeanFactoryPostProcessor差很少,都是先PriorityOrdered,而後Ordered,最後是普通的實現。

7.initMessageSource():初始化國際化資源。

8.initApplicationEventMulticaster():初始化事件廣播。

9.onRefresh();模板方法。

10.registerListeners():註冊事件監聽

11.finishBeanFactoryInitialization(beanFactory):初始化全部不是懶加載的單例bean。

12.finishRefresh():完成初始化以後的工做。

整個流程中最主要的其實就是步驟二、五、6和11。分別是xml配置加載Bean定義;初始化實現了BeanFactoryPostProcessor接口的實例,並執行對應的方法;初始化實現了BeanPostProcessor接口的實例;初始化全部非懶加載的單例bean。其餘代碼感興趣的能夠本身去了解,這裏不作過多分析。

相關文章
相關標籤/搜索