Spring Bean生命周期-registerBeanPost

作者: Real_man | 来源:发表于2018-10-10 08:19 被阅读3次

    ApplicationContext刷新的时候上一步提到了,先调用BeanFactoryPostProcessors预处理下BeanFactory,现在注册Bean processors来拦截Bean的创建。

    实例化,然后调用所有注册的BeanPostProcessor bean。如果指定了顺序,会按照顺序执行。
    必须在应用Bean实例化之前调用。

    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
            PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
        }
    

    分析

    先看到还是这个工具类,在上步的BeanFactoryPostProcessors中使用的也是它。


    image.png

    注册BeanPostProcessor的代码如下:

        public static void registerBeanPostProcessors(
                ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
          
          // 获取BeanFactory中注册的类型为BeanPostProcessor.class的bean名称。一般获取到的是实现了BeanPostProcessor接口的Bean
            String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
    
            // Register BeanPostProcessorChecker that logs an info message when
            // a bean is created during BeanPostProcessor instantiation, i.e. when
            // a bean is not eligible for getting processed by all BeanPostProcessors.
            // 注册一个BeanPostProcessorChecker,用来记录bean在BeanPostProcessor实例化时的信息。
            int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
            beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    
            // Separate between BeanPostProcessors that implement PriorityOrdered,
            // Ordered, and the rest.
            // 将BeanPostProcessors分为实现了PriorityOrdered,Ordered等类型
            List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
            List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
            List<String> orderedPostProcessorNames = new ArrayList<String>();
            List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
            for (String ppName : postProcessorNames) {
                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                    BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                    priorityOrderedPostProcessors.add(pp);
                    // 如果BeanPostProcessors也实现了MergedBeanDefinitionPostProcessor接口,加入internalPostProcessors
                    if (pp instanceof MergedBeanDefinitionPostProcessor) {
                        internalPostProcessors.add(pp);
                    }
                }
                else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                    orderedPostProcessorNames.add(ppName);
                }
                else {
                    nonOrderedPostProcessorNames.add(ppName);
                }
            }
    
            // First, register the BeanPostProcessors that implement PriorityOrdered.
            // 首先注册实现了PriorityOrdered接口的BeanPostProcessors
            sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
            registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    
            // Next, register the BeanPostProcessors that implement Ordered.
            // 然后,注册实现了Ordered的BeanPostProcessors
            List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
            for (String ppName : orderedPostProcessorNames) {
                BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                orderedPostProcessors.add(pp);
                if (pp instanceof MergedBeanDefinitionPostProcessor) {
                    internalPostProcessors.add(pp);
                }
            }
            sortPostProcessors(beanFactory, orderedPostProcessors);
            registerBeanPostProcessors(beanFactory, orderedPostProcessors);
    
            // Now, register all regular BeanPostProcessors.
            // 现在注册所有常规的BeanPostProcessors
            List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
            for (String ppName : nonOrderedPostProcessorNames) {
                BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                nonOrderedPostProcessors.add(pp);
                if (pp instanceof MergedBeanDefinitionPostProcessor) {
                    internalPostProcessors.add(pp);
                }
            }
            registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
    
            // Finally, re-register all internal BeanPostProcessors.
            // 最后注册,所有的internal,也就是实现MergedBeanDefinitionPostProcessor的BeanPostProcessors
            sortPostProcessors(beanFactory, internalPostProcessors);
            registerBeanPostProcessors(beanFactory, internalPostProcessors);
         
         //添加ApplicationListenerDetector的BeanPostProcessor
            beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
        }
    

    整体代码也不难理解,如函数名,就是做了注册BeanPostProcessor

    • 获取实现了BeanPostProcessor的bean Name,最开始Bean的信息注册到了beandifinitionMap中
    • 将获取到的BeanPostProcessor分类,分为PriorityOrdered,Ordered和常规的类型
    • 分别将PriorityOrdered,Ordered和常规的Bean添加进ApplicationContext的beanPostProcessors中,ApplicationContext的beanPostProcessors是ArrayList。
    BeanFactory.getBeanNamesForType具体实现

    其内部调用的是doGetBeanNamesForType

    • 遍历beanDefinitionNames判断是否符合要求是否为type
    • 遍历manualSingletonNames。

    内部有个处理是如果Bean是FactoryBean,其名称前面加上&

    private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit){
                // Check all bean definitions.
                // 检查所有的beanDefinitionNames。
            for (String beanName : this.beanDefinitionNames) {
                // Only consider bean as eligible if the bean name
                // is not defined as alias for some other bean.
                if (!isAlias(beanName)) {
                    try {
                        RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                        // Only check bean definition if it is complete.
                        if (!mbd.isAbstract() && (allowEagerInit ||
                                ((mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading())) &&
                                        !requiresEagerInitForType(mbd.getFactoryBeanName()))) {
                            // In case of FactoryBean, match object created by FactoryBean.
                            boolean isFactoryBean = isFactoryBean(beanName, mbd);
                            boolean matchFound = (allowEagerInit || !isFactoryBean || containsSingleton(beanName)) &&
                                    (includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type);
                            if (!matchFound && isFactoryBean) {
                                // In case of FactoryBean, try to match FactoryBean instance itself next.
                                beanName = FACTORY_BEAN_PREFIX + beanName;
                                matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type);
                            }
                            if (matchFound) {
                                result.add(beanName);
                            }
                        }
                    }
                   ....
            }
    
            // Check manually registered singletons too.
            for (String beanName : this.manualSingletonNames) {
                try {
                    // In case of FactoryBean, match object created by FactoryBean.
                    if (isFactoryBean(beanName)) {
                        if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
                            result.add(beanName);
                            // Match found for this bean: do not match FactoryBean itself anymore.
                            continue;
                        }
                        // In case of FactoryBean, try to match FactoryBean itself next.
                        beanName = FACTORY_BEAN_PREFIX + beanName;
                    }
                    // Match raw bean instance (might be raw FactoryBean).
                    if (isTypeMatch(beanName, type)) {
                        result.add(beanName);
                    }
                }
                ...
            }
    
            return StringUtils.toStringArray(result);
    }
    

    TODO

    • BeanFactory中beanDefinitionNames,manualSingletonNames等属性深入理解

    最后

    注册BeanPostProcessor和invokeBeanFactoryPostProcessors很像,并且没什么复杂逻辑。就是将已经注册到beanFacory的Bean筛选出BeanPostProcessor然后添加到ApplicationContext的beanPostProcessor集合中。

    相关文章

      网友评论

        本文标题:Spring Bean生命周期-registerBeanPost

        本文链接:https://www.haomeiwen.com/subject/yfwuaftx.html