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


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,等待后面的的順序調用

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM