Spring5源码解读系列5—invokeBeanFactoryPostProcessors

2021/6/16 1:21:15

本文主要是介绍Spring5源码解读系列5—invokeBeanFactoryPostProcessors,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一 概述

invokeBeanFactoryPostProcessor主要作用是实例化已经在容器中注册过的BeanFactoryPostProcessor接口的实现类,回调postProcessBeanFactory方法等。

invokeBeanFactoryPostProcessor源码调用链又长又复杂,容易把人绕晕,因此本文主要围绕着先使用,再研究源码顺序,逐步段解析,从易到难。

二 BeanFactoryPostProcessor接口及其应用

BeanFactory 后置处理器BeanFactoryPostProcessor接口是Spring留给用户自己拓展的接口。直接debug代码,基本上都是空方法,因此debug前需要将BeanFactoryPostProcessor接口的实现添加到Spring的配置文件中。

2.1 Spring配置文件

<bean id="myBeanPostProcessor" class="com.service.MyBeanPostProcessor"/>

2.2 应用代码

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    //构造函数
   public MyBeanFactoryPostProcessor() {
        System.out.println("这是MyBeanFactoryPostProcessor的构造器!");
    }

    //回调方法
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
            throws BeansException {
        System.out
                .println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");

    }

2.3 打印日志

执行过程中会打印下面的日志

 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beanFactoryPostProcessor'

这是MyBeanFactoryPostProcessor的构造器!
BeanFactoryPostProcessor调用postProcessBeanFactory方法

三 源码分析

3.1 invokeBeanFactoryPostProcessors方法

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

...
	}


protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		...
        	// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		
        //通过beanFactory获取类型为BeanFactoryPostProcessor的BeanName数组
        String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
        //根据bean初始化的优先级分为三个list容器
        //实现PriorityOrdered接口的bean优先级最高
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        //实现Ordered接口的bean优先级居中
		List<String> orderedPostProcessorNames = new ArrayList<>();
        //其他bean优先级居排在最后
        
        //变量BeanName
		for (String ppName : postProcessorNames) {
          //判断是否被执行过的后置处理器
			if (processedBeans.contains(ppName)) {
            //若是,则跳过不执行任何操作
				// skip - already processed in first phase above
			}
            //判断是否实现PriorityOrdered接口
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
             //若是,获取该bean并添加到priorityOrderedPostProcessors中
             //getBean的动作会检查当前 bean对象是否被实例化,如无则会触发bean的实例化,调用构造函数
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
             //判断是否实现Ordered接口
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
             //若是,添加到orderedPostProcessorNames中
				orderedPostProcessorNames.add(ppName);
			}
			else {
            //添加到nonOrderedPostProcessorNames中
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
        //排序
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        // 调用BeanFactoryPostProcessor实现类的postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
        //同理PriorityOrdered接口的实现类
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
       //同理PriorityOrdered接口的实现类
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		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...
        //在mergedBeanDefinitions中,将已经实例化的后置处理器实现类对应的bean的state设为false
        //清除元数据信息,包括 allBeanNamesByType,singletonBeanNamesByType等
    // 这是因为后处理器可能已经修改了原始元数据,像替换值中的占位符...
		beanFactory.clearMetadataCache();
	}

3.2 invokeBeanFactoryPostProcessors方法

private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
        //调用BeanFactoryPostProcessor实现类的postProcessBeanFactory方法
			postProcessor.postProcessBeanFactory(beanFactory);
		}
	}

3.3 getBeanFactoryPostProcessors方法

/**
	 * Return the list of BeanFactoryPostProcessors that will get applied
	 * to the internal BeanFactory.
	 */
	public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
       //获取已经注册的BeanFactoryPostProcessor列表,在默认情况下返回值为空
		return this.beanFactoryPostProcessors;
	}

四 BeanDefinitionRegistryPostProcessor接口及其应用

BeanDefinitionRegistryPostProcessor接口是BeanFactoryPostProcessor接口的子接口,但是对Bean的优先级而言,实现BeanDefinitionRegistryPostProcessor接口的Bean对象的优先级高于实现BeanFactoryPostProcessor接口的Bean对象。

4.1 Spring配置文件

<bean id="myBeanDefinitionRegistryPostProcessor" class="com.service.MyBeanDefinitionRegistryPostProcessor"/>

4.2 应用代码

public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    public MyBeanDefinitionRegistryPostProcessor() {
        System.out.println("这是MyBeanDefinitionRegistryPostProcessor的构造器!");
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("MyBeanDefinitionRegistryPostProcessor调用postProcessBeanDefinitionRegistry方法");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("MyBeanDefinitionRegistryPostProcessor调用postProcessBeanFactory方法");
    }
}

4.3 打印日志

执行过程中会打印下面的日志

这是MyBeanDefinitionRegistryPostProcessor的构造器!
MyBeanDefinitionRegistryPostProcessor调用postProcessBeanDefinitionRegistry方法
MyBeanDefinitionRegistryPostProcessor调用postProcessBeanFactory方法

五 源码分析2

invokeBeanFactoryPostProcessors源码很长,但是很多都是重复的。只要抓住主线,即Bean实例化过程的优先级:实现PriorityOrdered接口的Bean > 实现Ordered接口的Bean > 两者都没用实现的Bean,就可以轻松读懂!

5.1 invokeBeanFactoryPostProcessors

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

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
        //存储已经处理过的BeanDefinitionRegistryPostProcessors类型的Bean
		Set<String> processedBeans = new HashSet<>();

        //ConfigurableListableBeanFactory是BeanDefinitionRegistry接口的实现类,因此是其实例
		if (beanFactory instanceof BeanDefinitionRegistry) {
         //向上转型
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            
            //封装两个list容器,将beanFactoryPostProcessors中存储的BeanFactoryPostProcessor对象添加到regularPostProcessors容器,另外一个存储到registryProcessors容器中
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
            
        //上面的源码分析提到过,beanFactoryPostProcessors对象的容量默认为空,因此不会执行fo循环内容
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            //判断beanFactoryPostProcessors存储的对象是否属于BeanDefinitionRegistryPostProcessor,将对象分别存储到两个不同容器中
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
                            //调用BeanDefinitionRegistryPostProcessor实现类的postProcessBeanDefinitionRegistry方法
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}

			// 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.
            
            //下面这段代码主要用于实现PriorityOrdered接口的实现类,这类Bean的优先级最高          
            //这里的current是指当前ben工厂beanFactory
            //定义一个BeanDefinitionRegistryPostProcessor类型的集合容器,用于存储beanFactory中实例为BeanDefinitionRegistryPostProcessor的Bean
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            //获取类型为BeanDefinitionRegistryPostProcessor的BeanName数组
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
               //遍历包含BeanName数组
			for (String ppName : postProcessorNames) {
            //判断是否实现PriorityOrdered接口
            //实现PriorityOrdered接口的Bean实例化顺序的优先级更高
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                //若是,则放入currentRegistryProcessors中
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
            //排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			//添加到registryProcessors中
            registryProcessors.addAll(currentRegistryProcessors);
			//调用实现类的postProcessBeanDefinitionRegistry方法         invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            //清空currentRegistryProcessors容器
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
           //  这段代码通上面的类似,主要用于实现Ordered接口的实现类,这类Bean的优先级中等
			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();


			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            //  这段代码通上面的类似,主要用于没用实现PriorityOrdered和Ordered接口的实现类,这类Bean的优先级最低            
            //是否重试
			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();
			}


			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
            //回调registryProcessors和regularPostProcessors中存储Bean对象的postProcessBeanFactory方法
            postProcessBeanFactory            
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

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

六 参考文献

1)JDK7在线文档
https://tool.oschina.net/apidocs/apidoc?api=jdk_7u4
2) JDK8在线文档
https://docs.oracle.com/javase/8/docs/api/
3) Bruce Eckel. Java编程思想,第4版,2007,机械工业出版社
4)方腾飞,魏鹏,程晓明. Java并发编程的艺术,第1版,2015年,机械工业出版社
5)克雷格.沃斯. Spring实战,第5版,2020年,人民邮电出版社



这篇关于Spring5源码解读系列5—invokeBeanFactoryPostProcessors的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程