BeanPostProcessor 最佳實(shí)踐和實(shí)現(xiàn)原理。

作用

BeanPostProcessor也稱為Bean后置處理器,它是Spring中定義的接口,在Spring容器的創(chuàng)建過程中(具體為Bean初始化前后)會(huì)回調(diào)BeanPostProcessor中定義的兩個(gè)方法。

postProcessBeforeInitialization : 初始化bean前調(diào)用。
postProcessAfterInitialization : 初始化bean后調(diào)用。

源碼分析:

1、AbstractBeanFactory

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    //AbstractBeanFactory 初始化 BeanPostProcessor集合。
    private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
}

2、AbstractApplicationContext核心refrsh()方法中調(diào)用registerBeanPostProcessors

/**
* 該方法獲取所有實(shí)現(xiàn)BeanPostProcessor接口的Bean
* 并將對(duì)應(yīng)的Bean分組排序加入到BeanFacotory的BeanPostProcessor數(shù)組中。
*/
public static void registerBeanPostProcessors(
            ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
        //通過getBeanNamesForType 方法獲取容器中所有bean。
        String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        //BeanPostProcessor that logs an info message when a bean is created during
        //系統(tǒng)日志,BeanPostProcessor初始化時(shí)打印日志用。
        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
     
        /**
        * 對(duì)于BeanPostProcessor 分組排序集合申明。
        * priorityOrder:優(yōu)先級(jí)排序接口數(shù)組(優(yōu)先級(jí)order排在普通order前)
        * Order: 普通排序接口數(shù)組。
        * noOrder:無排序數(shù)組。
        * internal: 特殊BeanPostProcessor數(shù)組。
        */
        List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
        List<String> orderedPostProcessorNames = new ArrayList<>();
        List<String> nonOrderedPostProcessorNames = new ArrayList<>();
        //解析分組
        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                priorityOrderedPostProcessors.add(pp);
                if (pp instanceof MergedBeanDefinitionPostProcessor) {
                    internalPostProcessors.add(pp);
                }
            }
            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                orderedPostProcessorNames.add(ppName);
            }
            else {
                nonOrderedPostProcessorNames.add(ppName);
            }
        }
        //優(yōu)先級(jí)數(shù)組排序和注入到Beanfactory
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

        List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
        for (String ppName : orderedPostProcessorNames) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            orderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        //普通order排序和注入
        sortPostProcessors(orderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, orderedPostProcessors);

        List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
        for (String ppName : nonOrderedPostProcessorNames) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            nonOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
       //無排序注入
        registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
       //特殊數(shù)組排序和注入
        sortPostProcessors(internalPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, internalPostProcessors);
        //監(jiān)聽器相關(guān)處理
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }

3、Bean初始化是調(diào)用方法。AbstractAutowireCapableBeanFactory.initializeBean方法

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        }
        else {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            //初始化前調(diào)用方法
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
             //初始化Bean
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            //初始化后調(diào)用
            wrappedBean =applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
}

4:applyBeanPostProcessorsBeforeInitialization方法解析

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        //獲取容器中的所有BeanPostProcessors,循環(huán)調(diào)用postProcessBeforeInitialization方法。
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容