spring4 IOC的BeanFactory后置处理器

2020-09-04  本文已影响0人  sunpy

示例

public class PrintBeanFactoryPostProcessor implements BeanFactoryPostProcessor{

    public PrintBeanFactoryPostProcessor() {
        System.out.println("实例化PrintBeanFactoryPostProcessor");
    }
    
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        String[] beanNames = beanFactory.getBeanDefinitionNames();
        
        for (String beanName : beanNames) {
            System.out.println("beanName : " +beanName);
        }
    }
}
<beans:bean id="printBeanFactoryPostProcessor" class="cn.spy.spring.source.code.PrintBeanFactoryPostProcessor"></beans:bean>

public static void main(String[] args) {
      ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
}

IOC容器默认执行实现了BeanFactoryPostProcessor接口的类的方法。

后置处理器源码

执行BeanFactory后处理入口
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
    }

委派PostProcessorRegistrationDelegate类之invokeBeanFactoryPostProcessors方法实现

// 回调所有BeanFactory的后置处理器
public static void invokeBeanFactoryPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

    Set<String> processedBeans = new HashSet<String>();
    // beanFactory为BeanDefinitionRegistry类型,进行处理
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
        List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
                new LinkedList<BeanDefinitionRegistryPostProcessor>();
        // 硬编码注册的后处理器
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            // BeanDefinitionRegistryPostProcessor类型的后置处理器先执行
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                BeanDefinitionRegistryPostProcessor registryPostProcessor =
                        (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
                registryPostProcessors.add(registryPostProcessor);
            }
            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.
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

        // 缓存实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessors后置处理器和处理器名称
        List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
        for (String ppName : postProcessorNames) {
            // 匹配PriorityOrdered类型
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        OrderComparator.sort(priorityOrderedPostProcessors);
        registryPostProcessors.addAll(priorityOrderedPostProcessors);
        
        /**
         * 回调实现PriorityOrdered接口的
         * BeanDefinitionRegistryPostProcessors后置处理器的
         * postProcessBeanDefinitionRegistry方法
         */
        invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);

        // 缓存实现Ordered接口的BeanDefinitionRegistryPostProcessors后置处理器和处理器名称
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
        for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        OrderComparator.sort(orderedPostProcessors);
        registryPostProcessors.addAll(orderedPostProcessors);
        /**
         * 回调实现Ordered接口的
         * BeanDefinitionRegistryPostProcessors后置处理器的
         * postProcessBeanDefinitionRegistry方法
         */
        invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);

        // 调用所有其他BeanDefinitionRegistryPostProcessor后置处理器
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName)) {
                    BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
                    registryPostProcessors.add(pp);
                    processedBeans.add(ppName);
                    pp.postProcessBeanDefinitionRegistry(registry);
                    reiterate = true;
                }
            }
        }

        // 回调注册BeanDefinitionRegistryPostProcessor类型处理器
        invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
         // 回调注册BeanFactoryPostProcessor类型处理器
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }

    else {
        // 调用了注册上下文实例的后处理beanFactory
        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!
    String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    List<String> orderedPostProcessorNames = new ArrayList<String>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
    // 后处理器分类:PriorityOrdered、Ordered、自定义未实现优先级排序的接口的
    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);
        }
    }

    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    // 按照优先级进行排序
    OrderComparator.sort(priorityOrderedPostProcessors);
    // 回调实现PriorityOrdered接口的
    // BeanFactoryPostProcessors后置处理器的
    // postProcessBeanFactory方法
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    OrderComparator.sort(orderedPostProcessors);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // 最后,回调没有排序、优先级的实现BeanFactoryPostProcessors接口的postProcessBeanFactory方法
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        // 实例化后置处理器bean
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    // 回调postProcessBeanFactory方法
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
}

该方法中处理BeanFactoryPostProcessor主要分为BeanDefinitionRegistry类和普通实现的BeanFactoryPostProcessor接口的类。由于spring对于后处理器调用支持按照PriorityOrdered或者Ordered优先级顺序调用。如果我们要保证读取顺序,也需实现PriorityOrdered或者Ordered接口,所以前面的代码大多在将后置处理器进行分类,搜集到不同的List中,然后执行对应的postProcessBeanFactory回调方法。方法最后的代码就是没有优先级排序的普通的后置处理器,则遍历nonOrderedPostProcessorNames名称集合,通过BeanFactory进行实例化后置处理器bean(getBean方法实现)。然后再回调下postProcessBeanFactory方法。


解释:示例中PrintBeanFactoryPostProcessor (后置处理器bean),会先实例化,所以执行构造方法,打印构造器内容。然后回调postProcessBeanFactory方法,才会打印bean名称。


BeanPostProcessor和BeanFactoryPostProcessor区别

BeanPostProcessor是bean初始化前后回调的接口。

BeanPostProcessor接口
postProcessBeforeInitialization方法:bean初始化之前回调的方法。
postProcessAfterInitialization方法:bean初始化之后回调的方法。
BeanFactoryPostProcessor是beanFactory初始化后回调的接口。
BeanFactoryPostProcessor接口
postProcessBeanFactory方法:beanFactory初始化后回调的方法。
上一篇下一篇

猜你喜欢

热点阅读