码迷,mamicode.com
首页 > 编程语言 > 详细

Spring IOC 初始化刷新流程六:registerBeanPostProcessors(beanFactory)

时间:2020-12-11 12:18:18      阅读:10      评论:0      收藏:0      [点我收藏+]

标签:common   finally   调用   注册   一个   不能   factory   const   processor   

Spring IOC 初始化刷新流程:https://www.cnblogs.com/jhxxb/p/13609289.html

 

这一步主要是实例化和注册 beanFactory 中实现了 BeanPostProcessor 接口的 Bean。

什么是 BeanPostProcessor

/**
 * 接口中两个方法不能返回 null,如果返回 null 在后续的初始化方法中将报空指针异常,或者通过 getBean() 方法获取不到 bena 实例对象,
 * 因为后置处理器从 Spring IOC 容器中取出 bean 实例对象没有再次放回 IOC 容器中。
 *
 * BeanFactory 和 ApplicationContext 注册 Bean 的后置处理器不通点:
 * ApplicationContext 直接使用 @Bean 注解,就能向容器注册一个后置处理器,它注册 Bean 的时候,会先检测是否实现了 BeanPostProcessor 接口,
 * 并自动把它们注册为后置处理器。所以在使用 ApplicationContext 注册一个后置处理器和注册一个普通的 Bean 是没有区别的。
 * BeanFactory 必须显示的调用:void addBeanPostProcessor(BeanPostProcessor beanPostProcessor 才能注册进去。
 *
 * Spring 可以注册多个 Bean 的后置处理器,是按照注册的顺序进行调用的。若想定制顺序,可以标注 @Order 或者实现 Order 接口。
 */
public interface BeanPostProcessor {

    /**
     * 在 Bean 实例化/依赖注入完毕之后,自定义初始化方法执行之前调用
     * 自定义初始化方法:init-method、@PostConstruct、实现 InitailztingBean 接口等
     *
     * @param bean     这个 Bean 实例
     * @param beanName bean 名称*/
    @Nullable
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * 在上面基础上,初始化方法执行之后调用
     */
    @Nullable
    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

 

方法源码

先看 BeanFactory 的 getBeanPostProcessors() 返回的是什么

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    /** BeanPostProcessors to apply. */
    private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
        // Remove from old position, if any,先移除
        this.beanPostProcessors.remove(beanPostProcessor);
        // Track whether it is instantiation/destruction aware
        if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
            this.hasInstantiationAwareBeanPostProcessors = true;
        }
        if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
            this.hasDestructionAwareBeanPostProcessors = true;
        }
        // Add to end of list,再添加,这样就把 beanPostProcessors 添加到 List 的末尾
        this.beanPostProcessors.add(beanPostProcessor);
    }

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    public List<BeanPostProcessor> getBeanPostProcessors() {
        // 返回的是所有通过 BeanFactory#addBeanPostProcessor 方法添加进去的后置处理器,会存在这个 List 里面
        return this.beanPostProcessors;
    }

再看容器启动时,用 BeanFactory#addBeanPostProcessor 添加进去的 Bean 后置处理器

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // Configure the bean factory with context callbacks.
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // 这里

        // Register early post-processor for detecting inner beans as ApplicationListeners.
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // 这里

        // Detect a LoadTimeWeaver and prepare for weaving, if found.
        if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
            beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // 这里

public abstract class AbstractRefreshableWebApplicationContext extends AbstractRefreshableConfigApplicationContext implements ConfigurableWebApplicationContext, ThemeSource {
    @Override
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig)); // 这里

public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        int factoryId = System.identityHashCode(beanFactory);
        if (this.factoriesPostProcessed.contains(factoryId)) {
            throw new IllegalStateException("postProcessBeanFactory already called on this post-processor against " + beanFactory);
        }
        this.factoriesPostProcessed.add(factoryId);
        if (!this.registriesPostProcessed.contains(factoryId)) {
            // BeanDefinitionRegistryPostProcessor hook apparently not supported...
            // Simply call processConfigurationClasses lazily at this point then.
            processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
        }

        enhanceConfigurationClasses(beanFactory);
        beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory)); // 这里
    }

    private static class ImportAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

具体源码

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        // 委托给 PostProcessorRegistrationDelegate 去做
        PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }

final class PostProcessorRegistrationDelegate {
    public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

        // 从所有 Bean 定义中提取出 BeanPostProcessor 类型的 Bean,注意和 getBeanPostProcessors 的结果区分开来,虽然都是 BeanPostProcessor
        // 最初的 6 个 bean,有 2 个是 BeanPostProcessor:
        // AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor
        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.
        // 向 beanFactory 又 add 了一个 BeanPostProcessorChecker,且总数设置为了 getBeanPostProcessorCount 和 addBeanPostProcessor 的总和(+1表示自己)
        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        // beanProcessorTargetCount 表示的是处理器的总数,总数(包含两个位置的,用于后面的校验)
        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

        // Separate between BeanPostProcessors that implement PriorityOrdered,
        // Ordered, and the rest.
        // 先按优先级,归类 BeanPostProcessor
        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);
                // MergedBeanDefinitionPostProcessor 是在合并处理 Bean 定义的时候的回调。基本是框架内部使用的,用户不用管
                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.
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

        // Next, register the BeanPostProcessors that implement Ordered.
        List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
        for (String ppName : orderedPostProcessorNames) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            orderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        sortPostProcessors(orderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, orderedPostProcessors);

        // Now, register all regular BeanPostProcessors.
        List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
        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.
        sortPostProcessors(internalPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, internalPostProcessors);

        // Re-register post-processor for detecting inner beans as ApplicationListeners,
        // moving it to the end of the processor chain (for picking up proxies etc).
        // 最后此处需要注意的是:Spring 注册了一个 Bean 的后置处理器:ApplicationListenerDetector,它是用来检查所有的 ApplicationListener
        // 之前注册过,这里又注册一次:Re-register 重新注册这个后置处理器。把它移动到处理器链的最后面,最后执行(addBeanPostProcessor 是先 remove,然后 add)
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }

    // 把类型是 BeanPostProcessor 的 Bean,注册到 beanFactory 里去
    private static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
        for (BeanPostProcessor postProcessor : postProcessors) {
            beanFactory.addBeanPostProcessor(postProcessor);
        }
    }

    private static final class BeanPostProcessorChecker implements BeanPostProcessor {

至此,这一步完成。Spring 从所有的 @Bean 定义中抽取出来了 BeanPostProcessor,然后都注册进 beanPostProcessors,等待后面的的顺序调用

 

Spring IOC 初始化刷新流程六:registerBeanPostProcessors(beanFactory)

标签:common   finally   调用   注册   一个   不能   factory   const   processor   

原文地址:https://www.cnblogs.com/jhxxb/p/13957928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!