Spring源码分析之Bean工厂后置处理器(一)

引言

Spring在我们目前的开发中基本上必不可少,绝大多数的公司都使用Spring框架作为开发的基础架构,那么我们有必要了解Spring是怎么工作的,以及如何在工作中使用并扩展Spring。今天我们就先来讲解Spring中一个非常重要的概念:后置处理器。
Spring中有两种非常重要的后置处理器:

  1. bean工厂后置处理器
  2. bean后置处理器

其中Bean工厂后置处理器就是本节要讲的,它们会在Spring启动过程中,在实例化bean之前执行,它们主要用来扫描出后续需要进行实例化的bean,并注册成BeanDifinition,如Spring整合mabatis,具体可以参考我的另外两篇博文。
Spring继承mybatis源码分析(一)
Spring继承mybatis源码分析(二)

bean工厂后置处理器入口

大家先看下面这段代码,我们刚学Spring的时候,想要初始化一个Spring容器,首先会新建一个ApplicationContext上下文环境。

public static void main(String[] args) throws NoSuchMethodException {
	AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
	//ClassPathXmlApplicationContext xmlAc = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
	ac.register(AppConfig.class);
	ac.refresh();
}

如果是采用XML配置的方式,我们会使用ClassPathXmlApplicationContext,并且在配置文件中加上<context:component-scan base-package=“com.xxx”/>,用来扫描包下面的bean,如果是采用注解的方式我们一般使用AnnotationConfigApplicationContext,无论如何,他们最终都继承自抽象类AbstractApplicationContext,都会执行该抽象类的refresh方法,并且都会调用AnnotationConfigUtils.registerAnnotationConfigProcessors()方法,这个方法中会往Spring容器中注入ConfigurationClassPostProcessor,AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor等的BeanDifinition。不同之处在于XML形式会在执行refresh方法中的obtainFreshBeanFactory()创建beanFactory,然后解析XML,当解析到context:component-scan时执行AnnotationConfigUtils.registerAnnotationConfigProcessors(),而注解形式的讲会直接在初始化AnnotationConfigApplicationContext的属性AnnotatedBeanDefinitionReader reader时调用。

public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// 
		prepareRefresh();
	
		// Tell the subclass to refresh the internal bean factory.
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
	
		// 准备bean工厂,主要做了以下几点
		// 1. 设置了bean的类加载器
		// 2. 添加了ApplicationContextAwareProcessor,ApplicationListenerDetector的BeanPostProcessor
		// 3. 添加了部分默认的Spring系统bean依赖
		// 4. 添加了表达式解析器
		prepareBeanFactory(beanFactory);
	
		try {
			// 本类没做任何事,留作子类扩展用
			postProcessBeanFactory(beanFactory);
	
			// 执行BeanFactoryPostProcessor,
			invokeBeanFactoryPostProcessors(beanFactory);
	
			// 注册Spring自带的扫描出来的,以及系统自带的BeanPostProcessor,并排序
			registerBeanPostProcessors(beanFactory);
	
			// 初始化国际化相关的内容
			initMessageSource();
	
			// 初始事件广播器
			initApplicationEventMulticaster();
	
			// 注册其他bean或者其他操作,提供给子类扩展,默认不做任何事
			onRefresh();
	
			// 添加监听器
			registerListeners();
	
			// 实例化bean
			finishBeanFactoryInitialization(beanFactory);
	
			// 执行LifecycleProcessor,发布ContextRefreshed事件
			finishRefresh();
		}
	
		catch (BeansException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Exception encountered during context initialization - " +
						"cancelling refresh attempt: " + ex);
			}
	
			// Destroy already created singletons to avoid dangling resources.
			destroyBeans();
	
			// Reset 'active' flag.
			cancelRefresh(ex);
	
			// Propagate exception to caller.
			throw ex;
		}
	
		finally {
			// Reset common introspection caches in Spring's core, since we
			// might not ever need metadata for singleton beans anymore...
			resetCommonCaches();
		}
	}
}
Bean工厂后置处理器的执行

我们来看一下Spring中最重要的ConfigurationClassPostProcessor这个类的类图,

  1. 实现了一个BeanDefinitionRegistryPostProcessor接口,BeanDefinitionRegistryPostProcessor接口继承自BeanFactoryPostProcessor接口
  2. 另外还实现了一些Aware接口(主要用来注入一些属性,如Classloader,ResourceLoader,Enviroment)
  3. 还实现了PriorityOrdered接口,这个后面会用来,主要用来控制执行顺序
    在这里插入图片描述
    下面来看具体代码实现,执行过程基本秉持以下原则
  4. 系统初始化时加入的优先于通过bean扫描出来的
  5. 实现了PriorityOrdered的优先于实现了Ordered的,优先于没有实现以上两者的
  6. 实现了BeanDefinitionRegistryPostProcessor接口的优先于直接实现了BeanFactoryPostProcessor接口的

具体的详细说明见代码

我们这里要讲的ConfigurationClassPostProcessor会在invokeBeanFactoryPostProcessors()方法中执行。

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

	// 已经执行过的BeanFactoryPostProcessor的beanName
	Set<String> processedBeans = new HashSet<>();

	// 默认是DefaultListableBeanFactory,实现了BeanDefinitionRegistry
	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
		List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
		// 遍历程序员自己手动添加的beanFactoryPostProcessors, 以及spring如SpringBoot自己最开始添加的beanFactoryPostProcessors
		// 如果属于BeanDefinitionRegistryPostProcessor,则执行postProcessBeanDefinitionRegistry
		// ac.addBeanFactoryPostProcessor()
		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				BeanDefinitionRegistryPostProcessor registryProcessor =
						(BeanDefinitionRegistryPostProcessor) postProcessor;
				registryProcessor.postProcessBeanDefinitionRegistry(registry);
				registryProcessors.add(registryProcessor);
			}
			else {
				regularPostProcessors.add(postProcessor);
			}
		}

		// 首先执行实现了PriorityOrdered,BeanDefinitionRegistryPostProcessor的实例的postProcessBeanDefinitionRegistry方法
		// 这里我们就会执行本次说的ConfigurationClassPostProcessor类,这个类负责扫描配置类
		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

		// 获取到所有的BeanDefinitionRegistryPostProcessor类型的bean
		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);
		// 实现了BeanDefinitionRegistryPostProcessor的类加入到registryProcessors,后续需要调用BeanFactoryPostProcessor的postProcessBeanFactory方法
		registryProcessors.addAll(currentRegistryProcessors);
		// 执行postProcessBeanDefinitionRegistry方法,在该处,将执行ConfigurationClassPostProcessor,对配置类进行扫描,并注册BeanDifinition
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		currentRegistryProcessors.clear();

		// 按上面的流程执行实现了Ordered的BeanDefinitionRegistryPostProcessor
		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();

		// 最后执行其他所有的BeanDefinitionRegistryPostProcessor
		// while循环判断是否在执行postProcessBeanDefinitionRegistry方法的过程中,又出现了其他的BeanDefinitionRegistryPostProcessor,直到最后没有为止
		boolean reiterate = true;
		while (reiterate) {
			reiterate = false;
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
					reiterate = true;
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();
		}

		// 执行所有实现了BeanDefinitionRegistryPostProcessor接口的BeanFactoryPostProcessor的postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		//  执行所有Spring自带的或者由程序员手动添加的直接继承自BeanFactoryPostProcessor的postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	else {
		// Invoke factory processors registered with the context instance.
		invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

	// 获取直接实现了BeanFactoryPostProcessor的beanNames,此处会获取到实现了BeanDefinitionRegistryPostProcessor,但实现了后者的bean已经在processedBeans中,因此不会再次执行
	String[] postProcessorNames =
			beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

	List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	List<String> orderedPostProcessorNames = new ArrayList<>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
	// 分类,实现了PriorityOrdered,Ordered,和没有实现前两者的beanNames
	for (String ppName : postProcessorNames) {
		if (processedBeans.contains(ppName)) {
			// skip - already processed in first phase above
		}
		else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// 执行PriorityOrdered类的BeanFactoryPostProcessor
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

	// 执行Ordered类的BeanFactoryPostProcessor
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

	// 执行其他所有没有执行过的BeanFactoryPostProcessor
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : nonOrderedPostProcessorNames) {
		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

	// Clear cached merged bean definitions since the post-processors might have
	// modified the original metadata, e.g. replacing placeholders in values...
	beanFactory.clearMetadataCache();
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
	int registryId = System.identityHashCode(registry);
	if (this.registriesPostProcessed.contains(registryId)) {
		throw new IllegalStateException(
				"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
	}
	if (this.factoriesPostProcessed.contains(registryId)) {
		throw new IllegalStateException(
				"postProcessBeanFactory already called on this post-processor against " + registry);
	}
	this.registriesPostProcessed.add(registryId);

	processConfigBeanDefinitions(registry);
}
如何添加自定义bean后置处理器
  1. 首先按照上面的执行逻辑选择要实现的接口是BeanDefinitionRegistryPostProcessor还是BeanFactoryPostProcessor
  2. 将该类添加注解@Component,使其能被其前面的执行的后置处理器扫描出来并注册成bean
  3. 在方法中实现自己的逻辑,如扫描包下面的类

最经典的案例就是mybatis的整合,通过了一个@MapperScan,即注入了一个MapperScannerConfigurer类,这个类继承自BeanDefinitionRegistryPostProcessor。

@Component
public class MyBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {

	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	@Documented
	@interface Fallback{
		String value();
	}

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry);
		scanner.addIncludeFilter(new AnnotationTypeFilter(Fallback.class));
		int scan = scanner.scan("com.wugao.fallback");
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		//TODO 执行自己的逻辑
	}

}

下一节我们将详细介绍ConfigurationClassPostProcessor的执行过程,这个类是产生BeanDifinition的关键。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值