关于java:Spring源码之invokeBeanFactoryPostProcessors

35次阅读

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

Spring 源码之 invokeBeanFactoryPostProcessors

概述

invokeBeanFactoryPostProcessors 办法中次要是解决 BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor,BeanDefinitionRegistryPostProcessor 是 BeanFactoryPostProcessor 的子接口,具备更弱小的性能。这两个接口是 Spring 再初始化前一个重要的扩大点。

invokeBeanFactoryPostProcessors 源码剖析

public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
 
    // Invoke BeanDefinitionRegistryPostProcessors first, if any.
    Set<String> processedBeans = new HashSet<String>();
 
    // 判断 beanFactory 是否为 BeanDefinitionRegistry,beanFactory 为 DefaultListableBeanFactory,
    // 而 DefaultListableBeanFactory 实现了 BeanDefinitionRegistry 接口,因而这边为 true
    if (beanFactory instanceof BeanDefinitionRegistry) {BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        // 用于寄存一般的 BeanFactoryPostProcessor
        List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
        // 用于寄存 BeanDefinitionRegistryPostProcessor
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
 
        // 首先解决入参中的 beanFactoryPostProcessors
        // 遍历所有的 beanFactoryPostProcessors, 将 BeanDefinitionRegistryPostProcessor 和一般 BeanFactoryPostProcessor 辨别开
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                //  如果是 BeanDefinitionRegistryPostProcessor
                BeanDefinitionRegistryPostProcessor registryProcessor =
                        (BeanDefinitionRegistryPostProcessor) postProcessor;
                // 间接执行 BeanDefinitionRegistryPostProcessor 接口的 postProcessBeanDefinitionRegistry 办法
                registryProcessor.postProcessBeanDefinitionRegistry(registry); //@3
                //  增加到 registryProcessors(用于最初执行 postProcessBeanFactory 办法)
                registryProcessors.add(registryProcessor);
            } else {
                // 否则,只是一般的 BeanFactoryPostProcessor
                // 增加到 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<BeanDefinitionRegistryPostProcessor>();
 
        // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
        // 调用所有实现 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor 实现类
        //  找出所有实现 BeanDefinitionRegistryPostProcessor 接口的 Bean 的 beanName
        //@1
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        // 遍历 postProcessorNames
        for (String ppName : postProcessorNames) {
            // 校验是否实现了 PriorityOrdered 接口
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                //  获取 ppName 对应的 bean 实例, 增加到 currentRegistryProcessors 中,
                // beanFactory.getBean: 这边 getBean 办法会触发创立 ppName 对应的 bean 对象, 目前暂不深刻解析
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                // 将要被执行的退出 processedBeans,防止后续反复执行
                processedBeans.add(ppName);
            }
        }
        // 进行排序(依据是否实现 PriorityOrdered、Ordered 接口和 order 值来排序)
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        //  增加到 registryProcessors(用于最初执行 postProcessBeanFactory 办法)
        registryProcessors.addAll(currentRegistryProcessors);
        // 遍历 currentRegistryProcessors, 执行 postProcessBeanDefinitionRegistry 办法
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        // 执行结束后, 清空 currentRegistryProcessors
        currentRegistryProcessors.clear();
 
        // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
        // 调用所有实现了 Ordered 接口的 BeanDefinitionRegistryPostProcessor 实现类(过程跟下面的步骤 3 根本一样)// 找出所有实现 BeanDefinitionRegistryPostProcessor 接口的类, 这边反复查找是因为执行完下面的 BeanDefinitionRegistryPostProcessor,
        // 可能会新增了其余的 BeanDefinitionRegistryPostProcessor, 因而须要从新查找
       // @2
        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);
        //  遍历 currentRegistryProcessors, 执行 postProcessBeanDefinitionRegistry 办法
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();
 
        // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
        // 最初, 调用所有剩下的 BeanDefinitionRegistryPostProcessors
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            // 找出所有实现 BeanDefinitionRegistryPostProcessor 接口的类
            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);
                    //  如果有 BeanDefinitionRegistryPostProcessor 被执行, 则有可能会产生新的 BeanDefinitionRegistryPostProcessor,
                    // 因而这边将 reiterate 赋值为 true, 代表须要再循环查找一次
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            // 遍历 currentRegistryProcessors, 执行 postProcessBeanDefinitionRegistry 办法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();}
 
        // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
        // 调用所有 BeanDefinitionRegistryPostProcessor 的 postProcessBeanFactory 办法(BeanDefinitionRegistryPostProcessor 继承自 BeanFactoryPostProcessor)
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        // 最初, 调用入参 beanFactoryPostProcessors 中的一般 BeanFactoryPostProcessor 的 postProcessBeanFactory 办法
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    } else {
        // Invoke factory processors registered with the context instance.
        invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }
 
    // 到这里 , 入参 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!
    // 找出所有实现 BeanFactoryPostProcessor 接口的类
    //@3
    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<BeanFactoryPostProcessor>();
    // 用于寄存实现了 Ordered 接口的 BeanFactoryPostProcessor 的 beanName
    List<String> orderedPostProcessorNames = new ArrayList<String>();
    // 用于寄存一般 BeanFactoryPostProcessor 的 beanName
    List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
    // 遍历 postProcessorNames, 将 BeanFactoryPostProcessor 按实现 PriorityOrdered、实现 Ordered 接口、一般三种辨别开
    for (String ppName : postProcessorNames) {
        //  跳过曾经执行过的
        if (processedBeans.contains(ppName)) {// skip - already processed in first phase above} else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            // 增加实现了 PriorityOrdered 接口的 BeanFactoryPostProcessor
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            //  增加实现了 Ordered 接口的 BeanFactoryPostProcessor 的 beanName
            orderedPostProcessorNames.add(ppName);
        } else {
            // 增加剩下的一般 BeanFactoryPostProcessor 的 beanName
            nonOrderedPostProcessorNames.add(ppName);
        }
    }
 
    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    // 调用所有实现 PriorityOrdered 接口的 BeanFactoryPostProcessor
    // 对 priorityOrderedPostProcessors 排序
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    // 遍历 priorityOrderedPostProcessors, 执行 postProcessBeanFactory 办法
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
 
    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    // 调用所有实现 Ordered 接口的 BeanFactoryPostProcessor
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    for (String postProcessorName : orderedPostProcessorNames) {
        //  获取 postProcessorName 对应的 bean 实例, 增加到 orderedPostProcessors, 筹备执行
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    //  对 orderedPostProcessors 排序
    sortPostProcessors(orderedPostProcessors, beanFactory);
    // 遍历 orderedPostProcessors, 执行 postProcessBeanFactory 办法
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
 
    // Finally, invoke all other BeanFactoryPostProcessors.
    // 调用所有剩下的 BeanFactoryPostProcessor
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        // 11.1 获取 postProcessorName 对应的 bean 实例, 增加到 nonOrderedPostProcessors, 筹备执行
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    // 遍历 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...
    // 革除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType),// 因为后处理器可能曾经批改了原始元数据,例如,替换值中的占位符...
    beanFactory.clearMetadataCache();}

@1 这里会咱们能够看下 beanFactory 中只有 7 个 beanDefinition,其中只有 ConfigurationClassPostProcessor 是实现了 BeanDefinitionRegistryPostProcessor 接口
所以它会被优先执行。

ConfigurationClassPostProcessor 后置处理器是在 run()—>createApplicationContext()—>ApplicationContextFactory.create()—>
AnnotationConfigApplicationContext—->AnnotatedBeanDefinitionReader()—>
AnnotationConfigUtils.registerAnnotationConfigProcessors()增加的默认处理器。
@2 因为加载了 ConfigurationClassPostProcessor,零碎中可能新增一些实现了 BeanDefinitionRegistryPostProcessor 的类,对他们进行排序,遍历执行 postProcessBeanDefinitionRegistry 办法。
@3 加载所有实现了 BeanFactoryPostProcessor,执行 postProcessBeanFactory 办法
从代码执行的程序也能够晓得 BeanDefinitionRegistryPostProcessor 是在 BeanFactoryPostProcessor 之前执行

测试论证

@Component
public class BeanDefinitionRegistryPostProcessorOrder1 implements BeanDefinitionRegistryPostProcessor, Ordered {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("BeanDefinitionRegistryPostProcessorOrder1:::"+"postProcessBeanDefinitionRegistry");
    }

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

    @Override
    public int getOrder() {return 1;}
}

@Component
public class BeanDefinitionRegistryPostProcessorOrder2 implements BeanDefinitionRegistryPostProcessor, Ordered {

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

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {System.out.println("BeanDefinitionRegistryPostProcessorOrder2:::" + "postProcessBeanDefinitionRegistry");
    }
    
    @Override
    public int getOrder() {return 2;}
}


@Component
public class BeanFactoryPostProcessorOrder1 implements BeanFactoryPostProcessor, Ordered {

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

    @Override
    public int getOrder() {return 1;}
}


@Component
public class BeanFactoryPostProcessorOrder2 implements BeanFactoryPostProcessor, Ordered {

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

    @Override
    public int getOrder() {return 2;}
}


输入后果:BeanDefinitionRegistryPostProcessorOrder1:::postProcessBeanDefinitionRegistry
BeanDefinitionRegistryPostProcessorOrder2:::postProcessBeanDefinitionRegistry
BeanDefinitionRegistryPostProcessorOrder1:::postProcessBeanFactory
BeanDefinitionRegistryPostProcessorOrder2:::postProcessBeanFactory
BeanFactoryPostProcessorOrder1:::postProcessBeanFactory
BeanFactoryPostProcessorOrder2:::postProcessBeanFactory

正文完
 0