关于java:Spring源码之BeanFactoryPostProcessor后置处理器

4次阅读

共计 11703 个字符,预计需要花费 30 分钟才能阅读完成。

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();}
正文完
 0