Spring源码之BeanFactoryPostProcessor

一、前言

  • BeanFactoryPostProcessor: Spring的重要扩展点,增强beanFactory的功能;可以在加载解析BeanDefinition之后,可以对BeanDefinition进行修改;可以新增一些特殊的BeanPostProcessor,比如new Xxx(beanFactory)新增带有beanFactory的BeanPostProcessor;

  • BeanDefinitionRegistryPostProcessor: BeanFactoryPostProcessor的子接口,用于解析注册BeanDefinition,所以它是先于BeanFactoryPostProcessor执行。实现类中ConfigurationClassPostProcessor很重要。

  • ConfigurationClassPostProcessor: BeanFactoryPostProcessor的重要实现类,用于解析@Configuration标注的配置类,解析配置类上的注解,比如解析加载来自@ComponentScan扫描路径中的BeanDefinition、解析加载来自@ImportResource导入的配置文件中的BeanDefinition,会单开一篇文章讲解这个。

  • 代码位置: 在AbstractApplicationContext.refresh()中的invokeBeanFactoryPostProcessors环节执行。该环节的内容就是执行所有的BeanFactoryPostProcessor。

二、BeanFactoryPostProcessor的执行顺序

  • BeanFactoryPostProcessor与BeanDefinitionRegistryPostProcessor之间: 先执行BeanDefinitionRegistryPostProcessor,后执行BeanFactoryPostProcessor
  • 同类型之间:同类之间如果需要按顺序执行,需要实现Ordered接口并实现getOrder方法返一个整数值,比较器根据此整数进行排序,数值越低优先级越高,反之越低,取值返回是Integer.MIN_VALUE ~ Integer.MAX_VALUE。也可以实现Ordered的子接口PriorityOrdered,逻辑同上。执行顺序为 implement PriorityOrderedimplement Ordered其他

Ordered:

Spring源码之BeanFactoryPostProcessor_第1张图片

三、源码分析

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

		/*
		  为了防止处理器以错误的顺序执行,使用PriorityOrdered和Ordered接口排序
		 */

		// 存储所有处理器的名称
		Set<String> processedBeans = new HashSet<>();

		/*
		 首先调用beanFactoryPostProcessors参数中的.
		 */
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			// 保存BeanFactoryPostProcessor
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			// 保存BeanDefinitionRegistryPostProcessor
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			// 循环遍历beanFactoryPostProcessors,区分BeanFactory和BeanDefinitionRegistry
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					// 执行BeanDefinition的注册
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}

			// 存储当前将要执行的 RegistryPostProcessor.
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// 首先执行实现PriorityOrdered的 RegistryPostProcessor.
			// 根据类型在当前的BeanDefinition中匹配
			// 需要注意的是ConfigurationClassPostProcessor这个重要实现类,是在这个地方执行的,在同组中优先级最低
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					// 通过getBean的方式获取处理器
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			// 排序,规则是比较接口方法返回的数字谁的数字小,数字越小优先级越高,最低最高分别是Integer的最小值和最大值
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			// 执行加载BeanDefinition处理器
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			// 清空要处理的处理器的集合
			currentRegistryProcessors.clear();

			// 下一个处理实现Ordered接口的处理器.逻辑和PriorityOrdered一样
			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, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

			// 最后处理没有排序的 RegistryProcessor.
			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, beanFactory.getApplicationStartup());
				currentRegistryProcessors.clear();
			}

			// 执行集合中的BeanFactoryPostProcessor的postProcessBeanFactory方法
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// 只执行参数中的BeanFactoryPostProcessor的postProcessBeanFactory方法.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// 获取BeanFactoryPostProcessor的实现类的Name结合
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// 分离PriorityOrdered、Ordered与其他的BeanFactoryPostProcessors.

		// 实现PriorityOrdered的
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// 实现Ordered的
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// 没有排序的
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		// 循环分类
		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接口的处理器.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// 最后是没有排序的其他BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// 处理器有可能修改了元数据,所以要清空元数据缓存
		beanFactory.clearMetadataCache();
	}

四、简单实现

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {

    public MyBeanFactoryPostProcessor() {

        System.out.println("MyBeanFactoryPostProcessor() ....");
    }
    
    
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        // 修改指定bean的BeanDefinition
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition("");

        // 注册BeanPostProcessor
        beanFactory.addBeanPostProcessor(new MyBeanPostProcessor(beanFactory));
        
        // 屏蔽接口依赖
        beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
        
        // 等等....
    }

    @Override
    public int getOrder() {

        return Ordered.HIGHEST_PRECEDENCE;
    }
}

五、总结

  1. BeanFactoryPostProcessor用于加强BeanFactory的功能。
  2. BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子接口,用于注册更多的beanDefinition。
  3. PriorityOrdered 和 Ordered两个排序接口,PriorityOrdered 是Ordered的子类,getOrder返回的值越小优先级越高,Integer.MIN_VALUE 拥有最高优先级,而Integer.MAX_VALUE 则拥有最低优先级。
  4. BeanDefinitionRegistryPostProcessor先于BeanFactoryPostProcessor执行。
  5. 同类别之间,实现PriorityOrdered的 先于 实现Ordered的,最后是其他的处理器。

你可能感兴趣的:(spring原理及源码,spring,java,后端)