回顾

Spring 容器初始化流程(上)中我们分析了上下文环境的构建和Bean工程的构建及初始化流程,接下来我们继续深入Spring容器初始化的源码中,学习Spring框架原理,在本篇涉及到的源码包含Bean工厂的后置处理器注册调用、Bean后置处理器的注册、国际化、事件广播器等

废话不多说,接着上篇我们继续分析:

5. invokeBeanFactoryPostProcessors

激活各种BeanFactory处理器

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    // getBeanFactoryPostProcessors 获取的是 this.beanFactoryPostProcessors;
    //this.beanFactoryPostProcessors 只能通过 AbstractApplicationContext.addBeanFactoryPostProcessor 方法添加
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

    // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
    // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
}

invokeBeanFactoryPostProcessors(beanFactory)方法的主要的逻辑在PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors方法中。

在看代码前,我们先看看这个方法的执行流程,主要是获取并调用Bean工厂后置处理器的相关方法,达到动态修改BeanDefinition的能力,如使用BeanFactoryPostProcessor对BeanDefinition进行编辑,使用BeanDefinitionRegistryPostProcessor对BeanDefinition进行增删。

// PostProcessorRegistrationDelegate.java

public static void invokeBeanFactoryPostProcessors(
    ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors)
 
{

    // 定义一个 set 保存所有的 BeanFactoryPostProcessors
    Set<String> processedBeans = new HashSet<>();

    // 如果当前 BeanFactory 为 BeanDefinitionRegistry
    // 默认的 DefaultListableBeanFactory 实现了BeanDefinitionRegistry
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        // BeanFactoryPostProcessor 集合
        List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
        // BeanDefinitionRegistryPostProcessor 集合
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
        // 先迭代注册用户添加的 beanFactoryPostProcessors
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                // 如果是 BeanDefinitionRegistryPostProcessor,则调用 postProcessBeanDefinitionRegistry 进行注册,
                // 同时加入到 registryProcessors 集合中
                BeanDefinitionRegistryPostProcessor registryProcessor =
                    (BeanDefinitionRegistryPostProcessor) postProcessor;
                // 先执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法
                // 这个方法可提供动态修改BeanDefinition的能力
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                registryProcessors.add(registryProcessor);
            }
            else {
                // 否则当做普通的 BeanFactoryPostProcessor 处理
                // 添加到 regularPostProcessors 集合中即可,便于后面做后续处理
                regularPostProcessors.add(postProcessor);
            }
        }

        // 用于保存当前处理的 BeanDefinitionRegistryPostProcessor
        List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

        // 首先处理实现了 PriorityOrinvokeBeanFactoryPostProcessorsdered (有限排序接口)的 BeanDefinitionRegistryPostProcessor
        String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, truefalse);
        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        // 排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        // 加入registryProcessors集合
        registryProcessors.addAll(currentRegistryProcessors);
        // 调用所有实现了 PriorityOrdered 的 BeanDefinitionRegistryPostProcessors 的 postProcessBeanDefinitionRegistry()
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        // 清空,以备下次使用
        currentRegistryProcessors.clear();

        // 其次,调用是实现了 Ordered(普通排序接口)的 BeanDefinitionRegistryPostProcessors
        // 逻辑和 上面一样
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, truefalse);
        for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();

        // 最后调用其他的 BeanDefinitionRegistryPostProcessors
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            // 获取 BeanDefinitionRegistryPostProcessor
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, truefalse);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName)) {
                    // 没有包含在 processedBeans 中的(因为包含了的都已经处理了)
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            // 与上面处理逻辑一致
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }

        // 调用所有 BeanDefinitionRegistryPostProcessor (包括手动注册和通过配置文件注册)
        // 和 BeanFactoryPostProcessor(只有手动注册)的回调函数(postProcessBeanFactory())
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }

    else {
        // 如果不是 BeanDefinitionRegistry 只需要调用其回调函数(postProcessBeanFactory())即可
        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, truefalse);

    // 这里同样需要区分 PriorityOrdered 、Ordered 和 no Ordered
    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (processedBeans.contains(ppName)) {
            // 已经处理过了的,跳过
        }
        else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            // PriorityOrdered
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            // Ordered
            orderedPostProcessorNames.add(ppName);
        }
        else {
            // no Ordered
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, PriorityOrdered 接口
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // Next, Ordered 接口
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // Finally, no ordered
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

    // Clear cached merged bean definitions since the post-processors might have
    // modified the original metadata, e.g. replacing placeholders in values...
    beanFactory.clearMetadataCache();
}

配置注释和上面的执行流程,应该比较清楚。

扩展点:关于BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor的区别

6. registerBeanPostProcessors

注册拦截Bean创建的Bean处理器,即注册 BeanPostProcessor

BeanFactoryPostProcessor 一样,也是委托给 PostProcessorRegistrationDelegate 来实现的。

// AbstractApplicationContext.java

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

按照惯例,先看看执行流程:

主要是获取并注册所有的BeanPostProcessor,结合上图,看下面的代码就会跟清晰:

// PostProcessorRegistrationDelegate.java

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

    // 所有的 BeanPostProcessors
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, truefalse);

    // 注册 BeanPostProcessorChecker
    // 主要用于记录一些 bean 的信息,这些 bean 不符合所有 BeanPostProcessors 处理的资格
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // 区分 PriorityOrdered、Ordered 、 no ordered
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    // 存放MergedBeanDefinitionPostProcessor类型的处理器
    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);
        }
    }

    // 先注册优先排序的处理器
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // 再处理普通排序的处理器
    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);

    // 然后注册普通的处理器
    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);

    // 最后,重新注册所有MergedBeanDefinitionPostProcessor类型的bean。
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);

    // 重新注册用来自动探测内部ApplicationListener的post-processor
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
  • MergedBeanDefinitionPostProcessor
  • 继承了BeanPostProcessor,额外提供了postProcessMergedBeanDefinition方法,该方法把bean的BeanDefinition信息和beanType也传递到处理器中,处理器可根据传参做进一步的处理
  • ApplicationListenerDetector
  • 该处理器的作用是扫描出所有单例的ApplicationListener,并添加到Spring上下文中
7. initMessageSource

初始化上下文中的资源文件,如国际化文件的处理等 。

其实该方法就是初始化一个 MessageSource 接口的实现类,主要用于国际化/i18n

// AbstractApplicationContext.java

protected void initMessageSource() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
        // 包含 “messageSource” 的bean
        this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
        if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
            // 如果有父类
            // HierarchicalMessageSource 分级处理的 MessageSource
            HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
            if (hms.getParentMessageSource() == null) {
                // 如果没有注册父 MessageSource,则设置为父类上下文的的 MessageSource
                hms.setParentMessageSource(getInternalParentMessageSource());
            }
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Using MessageSource [" + this.messageSource + "]");
        }
    }
    else {
        // 使用 空 MessageSource
        DelegatingMessageSource dms = new DelegatingMessageSource();
        dms.setParentMessageSource(getInternalParentMessageSource());
        this.messageSource = dms;
        // 注册到beanFactory中
        beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
        }
    }
}

方法比较简单,主要是初始化一个名为messageSource的bean,用于国际化

8. initApplicationEventMulticaster

初始化上下文事件广播器

// AbstractApplicationContext.java

protected void initApplicationEventMulticaster() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        // 如果存在 applicationEventMulticaster bean,则获取并赋值
        this.applicationEventMulticaster =
                beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isTraceEnabled()) {
            logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    else {
        // 没有则新建 SimpleApplicationEventMulticaster,并完成 bean 的注册
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
                    "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
        }
    }
}

类似initMessageSource ,如果当前容器中存在 applicationEventMulticaster 的 bean,则对 applicationEventMulticaster 赋值,否则新建一个 SimpleApplicationEventMulticaster 的对象(默认的),并完成注册。

9. onRefresh

空实现,给子类扩展初始化其他Bean

// AbstractApplicationContext.java

protected void onRefresh() throws BeansException {
    // For subclasses: do nothing by default.
}

预留给 AbstractApplicationContext 的子类用于初始化其他特殊的 bean,该方法需要在所有单例 bean 初始化之前调用。

结语

到此,Spring容器的初始化流程已经走完三分之二了,坚持到这里的都是大佬啊,佩服佩服,那么继续乘胜追击吧:Spring 容器初始化流程(下)