Spring源码之BeanFactoryPostProcessor(后置处理器)。

有点程度的Spring开发人员想必都晓得BeanFactoryPostProcessor也就是常说的后置管理器,这是Spirng生命周期中的一个接口,实现这个接口能够在beanFactory初始化前做一些事。

咱们熟知的Spring和Mybatis的联合,正是因为Mybatis实现了BeanFactoryPostProcessor,它的重要性显而易见,深刻了解他对于切入Mybatis源码有着粗浅的意义。

如下图是简略的利用:

还是先贴上refresh()的源码

    @Override    public void refresh() throws BeansException, IllegalStateException {        synchronized (this.startupShutdownMonitor) {            // Prepare this context for refreshing.            //1、刷新前的筹备            prepareRefresh();            // Tell the subclass to refresh the internal bean factory.            //2、将会初始化 BeanFactory、加载 Bean、注册 Bean            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();            // Prepare the bean factory for use in this context.            //3、设置 BeanFactory 的类加载器,增加几个 BeanPostProcessor,手动注册几个非凡的 bean            prepareBeanFactory(beanFactory);            try {                //4、模板办法                // Allows post-processing of the bean factory in context subclasses.                postProcessBeanFactory(beanFactory);                // Invoke factory processors registered as beans in the context.                //执行BeanFactory后置处理器                invokeBeanFactoryPostProcessors(beanFactory);                // 5、Register bean processors that intercept bean creation.                //注册bean后置处理器                registerBeanPostProcessors(beanFactory);                // Initialize message source for this context.                //国际化                initMessageSource();                // Initialize event multicaster for this context.                initApplicationEventMulticaster();                // Initialize other special beans in specific context subclasses.                //6、模板办法--springboot实现了这个办法                onRefresh();                // Check for listener beans and register them.                //7、注册监听器                registerListeners();                // Instantiate all remaining (non-lazy-init) singletons.                //8、实现bean工厂的初始化**办法**********************************************                finishBeanFactoryInitialization(beanFactory);                //9、 Last step: publish corresponding event.                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();            }        }    }

benafactory源码的解决位于第三个地位。

次要波及到两个办法postProcessBeanFactory(beanFactory);

和invokeBeanFactoryPostProcessors(beanFactory);

postProcessBeanFactory(beanFactory)点进去发现是一个空办法,具体的执行在invokeBeanFactoryPostProcessors(beanFactory);中

咱们在invokeBeanFactoryPostProcessors办法上打断点一探到底。第一次看的时候感觉这是什么玩意,这么长,耐住性子一步步的往下看。

办法虽长大略总结一下就是,判断beanFactory类型,而后将注册的BeanPostFactory放入、排好程序、执行。

invokeBeanFactoryPostProcessors 办法的内容其实比拟少,大部分过程在正文都曾经写分明,这边在略微总结一下。

整个 invokeBeanFactoryPostProcessors 办法围绕两个接口,BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor,其中 BeanDefinitionRegistryPostProcessor 继承了 BeanFactoryPostProcessor 。

BeanDefinitionRegistryPostProcessor 次要用来在惯例 BeanFactoryPostProcessor 检测开始之前注册其余 Bean 定义,说的简略点,就是 BeanDefinitionRegistryPostProcessor 具备更高的优先级,执行程序在 BeanFactoryPostProcessor 之前。

具体的过程看正文吧

    public static void invokeBeanFactoryPostProcessors(            ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {        // Invoke BeanDefinitionRegistryPostProcessors first, if any.        Set<String> processedBeans = new HashSet<>();        // 1.判断beanFactory是否为BeanDefinitionRegistry,beanFactory为DefaultListableBeanFactory,        // 而DefaultListableBeanFactory实现了BeanDefinitionRegistry接口,因而这边为true        if (beanFactory instanceof BeanDefinitionRegistry) {            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;            // 用于寄存一般的BeanFactoryPostProcessor            List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();            // 用于寄存BeanDefinitionRegistryPostProcessor            List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();            // 2.首先解决入参中的beanFactoryPostProcessors            // 遍历所有的beanFactoryPostProcessors, 将BeanDefinitionRegistryPostProcessor和一般BeanFactoryPostProcessor辨别开            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {                    // 2.1 如果是BeanDefinitionRegistryPostProcessor                    BeanDefinitionRegistryPostProcessor registryProcessor =                            (BeanDefinitionRegistryPostProcessor) postProcessor;                    // 2.1.1 间接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry办法                    registryProcessor.postProcessBeanDefinitionRegistry(registry);                    // 2.1.2 增加到registryProcessors(用于最初执行postProcessBeanFactory办法)                    registryProcessors.add(registryProcessor);                }                else {                    // 2.2 否则,只是一般的BeanFactoryPostProcessor                    // 2.2.1 增加到regularPostProcessors(用于最初执行postProcessBeanFactory办法)                    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.            // 用于保留本次要执行的BeanDefinitionRegistryPostProcessor            List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();            // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.            // 3.调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类            // 3.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName            String[] postProcessorNames =                    beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);            // 3.2 遍历postProcessorNames            for (String ppName : postProcessorNames) {                // 3.3 校验是否实现了PriorityOrdered接口                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {                    // 3.4 获取ppName对应的bean实例, 增加到currentRegistryProcessors中,                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));                    // 3.5 将要被执行的退出processedBeans,防止后续反复执行                    processedBeans.add(ppName);                }            }            // 3.6 进行排序(依据是否实现PriorityOrdered、Ordered接口和order值来排序)            sortPostProcessors(currentRegistryProcessors, beanFactory);            // 3.7 增加到registryProcessors(用于最初执行postProcessBeanFactory办法)            registryProcessors.addAll(currentRegistryProcessors);            // 3.8 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry办法            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);            // 3.9 执行结束后, 清空currentRegistryProcessors            currentRegistryProcessors.clear();            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.            // 4.调用所有实现了Ordered接口的BeanDefinitionRegistryPostProcessor实现类(过程跟下面的步骤3根本一样)            // 4.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类, 这边反复查找是因为执行完下面的BeanDefinitionRegistryPostProcessor,            // 可能会新增了其余的BeanDefinitionRegistryPostProcessor, 因而须要从新查找            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);            for (String ppName : postProcessorNames) {                // 校验是否实现了Ordered接口,并且还未执行过                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);            // 4.2 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry办法            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);            currentRegistryProcessors.clear();            // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.            // 5.最初, 调用所有剩下的BeanDefinitionRegistryPostProcessors            boolean reiterate = true;            while (reiterate) {                reiterate = false;                // 5.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类                postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);                for (String ppName : postProcessorNames) {                    // 5.2 跳过曾经执行过的                    if (!processedBeans.contains(ppName)) {                        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));                        processedBeans.add(ppName);                        // 5.3 如果有BeanDefinitionRegistryPostProcessor被执行, 则有可能会产生新的BeanDefinitionRegistryPostProcessor,                        // 因而这边将reiterate赋值为true, 代表须要再循环查找一次                        reiterate = true;                    }                }                sortPostProcessors(currentRegistryProcessors, beanFactory);                registryProcessors.addAll(currentRegistryProcessors);                // 5.4 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry办法                invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);                currentRegistryProcessors.clear();            }            // Now, invoke the postProcessBeanFactory callback of all processors handled so far.            // 6.调用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory办法(BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor)            invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);            // 7.最初, 调用入参beanFactoryPostProcessors中的一般BeanFactoryPostProcessor的postProcessBeanFactory办法            invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);        }        else {            // Invoke factory processors registered with the context instance.            invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);        }        // Do not initialize FactoryBeans here: We need to leave all regular beans        // uninitialized to let the bean factory post-processors apply to them!        // 到这里 , 入参beanFactoryPostProcessors和容器中的所有BeanDefinitionRegistryPostProcessor曾经全副处理完毕,        // 上面开始解决容器中的所有BeanFactoryPostProcessor        // Do not initialize FactoryBeans here: We need to leave all regular beans        // uninitialized to let the bean factory post-processors apply to them!        // 8.找出所有实现BeanFactoryPostProcessor接口的类        String[] postProcessorNames =                beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);        // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,        // Ordered, and the rest.        // 用于寄存实现了PriorityOrdered接口的BeanFactoryPostProcessor        List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();        // 用于寄存实现了Ordered接口的BeanFactoryPostProcessor的beanName        List<String> orderedPostProcessorNames = new ArrayList<>();        // 用于寄存一般BeanFactoryPostProcessor的beanName        List<String> nonOrderedPostProcessorNames = new ArrayList<>();        // 8.1 遍历postProcessorNames, 将BeanFactoryPostProcessor按实现PriorityOrdered、实现Ordered接口、一般三种辨别开        for (String ppName : postProcessorNames) {            // 8.2 跳过曾经执行过的            if (processedBeans.contains(ppName)) {                // skip - already processed in first phase above            }            else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {                // 8.3 增加实现了PriorityOrdered接口的BeanFactoryPostProcessor                priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));            }            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {                // 8.4 增加实现了Ordered接口的BeanFactoryPostProcessor的beanName                orderedPostProcessorNames.add(ppName);            }            else {                // 8.5 增加剩下的一般BeanFactoryPostProcessor的beanName                nonOrderedPostProcessorNames.add(ppName);            }        }        // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.        // 9.调用所有实现PriorityOrdered接口的BeanFactoryPostProcessor        // 9.1 对priorityOrderedPostProcessors排序        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);        // 9.2 遍历priorityOrderedPostProcessors, 执行postProcessBeanFactory办法        invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);        // Next, invoke the BeanFactoryPostProcessors that implement Ordered.        // 10.调用所有实现Ordered接口的BeanFactoryPostProcessor        List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();        for (String postProcessorName : orderedPostProcessorNames) {            // 10.1 获取postProcessorName对应的bean实例, 增加到orderedPostProcessors, 筹备执行            orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));        }        // 10.2 对orderedPostProcessors排序        sortPostProcessors(orderedPostProcessors, beanFactory);        // 10.3 遍历orderedPostProcessors, 执行postProcessBeanFactory办法        invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);        // Finally, invoke all other BeanFactoryPostProcessors.        // 11.调用所有剩下的BeanFactoryPostProcessor        List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();        for (String postProcessorName : nonOrderedPostProcessorNames) {            // 11.1 获取postProcessorName对应的bean实例, 增加到nonOrderedPostProcessors, 筹备执行            nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));        }        // 11.2 遍历nonOrderedPostProcessors, 执行postProcessBeanFactory办法        invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);        // Clear cached merged bean definitions since the post-processors might have        // modified the original metadata, e.g. replacing placeholders in values...        // 12.革除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType),        // 因为后处理器可能曾经批改了原始元数据,例如, 替换值中的占位符...        beanFactory.clearMetadataCache();    }