Spring源码学习-IOC初始化过程-refresh()方法揭秘

前面两篇分别讲了Spring初始化容器的时候XML配置方式和注解方式如何解析注册BeanDefinition的整个过程。Spring在初始化 ApplicationContext容器的过程中注册BeanDefinition只是其中的一个步骤,其中还有很多处理比如初始化国际化资源、应用事件广播、应用事件监听等都是在抽象类AbstractApplicationContext的refresh()方法中完成的。

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

1.prepareRefresh():容器刷新前的准备,设置了开始时间、状态、验证所有标记为必需的属性是否可解析和一个模板方法initPropertySources()。

2.obtainFreshBeanFactory():里面两个模板方法refreshBeanFactory()和getBeanFactory()。看过之前xml配置方式注册BeanDefinition的应该知道入口就是AbstractRefreshableApplicationContext的refreshBeanFactory()。getBeanFactory()返回子类创建的bean factory实例,AbstractApplicationContext中不存在BeanFactory的实例,所以提供模板方法由子类具体创建提供。

3.prepareBeanFactory(beanFactory):容器使用前对bean工厂进行一些处理属性设置。

4.postProcessBeanFactory(beanFactory):模板方法提供给子类对bean工厂进行一些处理。

5.invokeBeanFactoryPostProcessors(beanFactory):这是一个重点,也是一个扩展点,同时用java做配置时的扫描注册BeanDefinition的入口也在这里。

首先初始化类型为BeanDefinitionRegistryPostProcessors并且实现了接口PriorityOrdered(高优先级)的bean并执行postProcessBeanDefinitionRegistry方法,ConfigurationClassPostProcessor就是在这里执行然后调用doscan方法扫描注册bean定义。

// 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 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方法

// 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 priorityOrderedPostProcessors = new ArrayList<>();
	List internalPostProcessors = new ArrayList<>();
	List orderedPostProcessorNames = new ArrayList<>();
	List 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 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 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():完成初始化之后的工作。

整个流程中最主要的其实就是步骤2、5、6和11。分别是xml配置加载Bean定义;初始化实现了BeanFactoryPostProcessor接口的实例,并执行对应的方法;初始化实现了BeanPostProcessor接口的实例;初始化所有非懒加载的单例bean。其他代码感兴趣的可以自己去了解,这里不做过多分析。

你可能感兴趣的:(Spring源码学习-IOC初始化过程-refresh()方法揭秘)