(二)ApplicationContext的启动以及初始化过程

在查看SpringBoot的源码时,可以看到构造完ConfigurableApplicationContext实例后,是通过调用ConfigurableApplicationContext中的refresh方法
来触发容器的一切处理流程的。

1.关于AbstractApplicationContext的refresh()方法

该方法是触发容器加载BeanDefinition以及创建对象等等一切操作的始发点,定义了作为应用上下文对象的一个抽象层面的标准流程。
所有spring应用上下文的初始化都是基于这个标准流程的。
@Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            //设置容器启动开始时间,容器启动状态、初始化环境配置等等
            prepareRefresh();

            //获取beanFactory并触发loadBeanDefinitions,默认是创建DefaultListableBeanFactory
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            //准备工作,对beanFactory作基本的配置工作
            prepareBeanFactory(beanFactory);

            try {
                //给子类预留的beanFacotry已准备完毕执行BeanFactoryPostProcessors之前的一个hook
                postProcessBeanFactory(beanFactory);

                //上面AnnotationConfigUtils注册的PostProcessors实际都会注册到这里的beanFactory中
                //这里通过PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
                //来执行所有关于Factory的Processors
                invokeBeanFactoryPostProcessors(beanFactory);

                //这里虽然还没有正式开始实例化对象工厂中的实例,但是BeanDefinition都已准备完毕,因此已经可以通过类型获取
                //所有对应的实现了BeanPostProcessor的 BeanDefinition,然后将对应的类注册到beanFactory中
                registerBeanPostProcessors(beanFactory);

                //这个是spring容器对国际化的实现,可以处理有本地化需求的信息
                initMessageSource();

                //这里是对容器事件广播的实现类初始化默认是使用SimpleApplicationEventMulticaster
                initApplicationEventMulticaster();

                //给子类提供的hook
                onRefresh();

                //这里实现注册监听容器事件的监听者
                registerListeners();

                //这里是实现对容器内所有单例对象的实例化
                finishBeanFactoryInitialization(beanFactory);

                //到这refresh的整个过程就基本完成了,这里主要做容器refresh完毕的事件发布,以及实现容器内对Lifecycle的支持(start)
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

1.1. 查看prepareRefresh();执行的细节

protected void prepareRefresh() {
    //设置容器状态
    this.startupDate = System.currentTimeMillis();
    this.closed.set(false);
    this.active.set(true);

    if (logger.isInfoEnabled()) {
        logger.info("Refreshing " + this);
    }

    //对propertySources作进一步初始化处理的一个hook,例如spring boot拓展的web容器对servletContext servletConfig转换为propertySource放到environment中
    initPropertySources();

    //校验environment中的必须的存在的配置信息是否存在,这里在查看Environment源码时,再看spring对配置propertySource怎么划分哪些是必要配置,哪些是可选配置的
    getEnvironment().validateRequiredProperties();

    //这里容器事件的publisher还未初始化,如果publisher初始化前注册的ApplicationEvents会注册到这里,待后面一起发布。
    this.earlyApplicationEvents = new LinkedHashSet<>();
}

1.2. 查看 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();的执行细节

看是如何获取的BeanFacotry,
虽然ApplicationContext实现了ListableBeanFactory与HierarchicalBeanFactory跟BeanFactory有关的接口,不过具体的接口实现是通过委托给了
这里获取的ConfigurableListableBeanFactory来处理的。
从下面的obtainFreshBeanFactory()方法中可以看到,AbstractApplicationContext并没有作具体实现,而是通过两个抽象方法定义了refresh的过程
只是定义了 refreshBeanFactory(); 加上 getBeanFactory();这两个抽象操作,对obtainFreshBeanFactory()这一步作了个细分(刷新、获取)。
其中refreshBeanFactory()与getBeanFactory()在AbstractRefreshableApplicationContext中进行实现的。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //对于可能已存在的BeanFacotry进行refresh
    refreshBeanFactory();
    //获取并返回具体的BeanFacotry
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (logger.isDebugEnabled()) {
        logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
    }
    return beanFactory;
}
下面查看在AbstractRefreshableApplicationContext中的refreshBeanFactory();方法
这里定义了BeanFactory创建以及初始配置、loadBeanDefinition的操作
@Override
protected final void refreshBeanFactory() throws BeansException {
    //检查是否存在beanFacotry,如果是初次refresh操作是不存在的
    if (hasBeanFactory()) { 
        destroyBeans();     //对实现了destory生命周期的对象做 destory回调
        closeBeanFactory(); //实现AbstractApplicationContext中定义的关闭BeanFactory方法,这里就是将this.beanFactory引用置为null
    }
    try {
        //通过new DefaultListableBeanFactory(getInternalParentBeanFactory())创建DefaultListableBeanFactory,getInternalParentBeanFactory()获取的是
        //当前应用上下文中设置的父上下文(ConfigurableApplicationContext)对象中的BeanFactory获取父上下文(ApplicationContext)作为BeanFacotry的父级
        //因此,如果是一个有子父关系的容器,那么它内部的BeanFactory也会建立子父关系,子容器refresh并不会丢失BeanFactory的中的子父关系。
        DefaultListableBeanFactory beanFactory = createBeanFactory();
        beanFactory.setSerializationId(getId());
        //配置对象工厂
        customizeBeanFactory(beanFactory);
        //这里基于应用上下文给beanFactory进行一次BeanDefinition的加载,
        //如:ClassPathXmlApplicationContext中构造时指定了xml资源路径会在此触发解析xml中的BeanDefinition
        loadBeanDefinitions(beanFactory);
        synchronized (this.beanFactoryMonitor) {
            //保持一个引用,供容器做BeanFactory相关操作的委托调用
            this.beanFactory = beanFactory;
        }
    }
    catch (IOException ex) {
        throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
    }
}

1.3.查看prepareBeanFactory(beanFactory);的执行细节

这里是对beanFactory作的一个应用层面上的配置。
应用上下文相关的接口注入是在这里处理的.
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    //统一BeanFactory与应用上下文对象的ClassLoader
    beanFactory.setBeanClassLoader(getClassLoader());
    //实现SPEL表达式的解析器
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

    //这个添加的是一些基于ResourceLoader的PropertyEditorRegistrar用来注册相关的属性编辑器PropertyEditor,PropertyEditor是java内省中定义的接口
    //功能就是支持通过string类型来编辑属性值,例如:通过字符串给long类型设置值,可以是输入longEditor.setAsText("1000");
    //其实实现很简单,就是将string转换为Long进行修改值即可,这里是spring拓展一些的PropertyEditor的拓展
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    //这个是关于ApplicationContext的一些对象的接口注入实现,该processor实现的是BeanPostProcessor,因此是在bean创建的相关回调阶段,然后判断接口类型,
    //执行对应的注入方法
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    //下面六种对象都是通过ApplicationContextAwareProcessor来执行接口注入的
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

    //通过下面的接口可以将这四个对象由依赖注入,注到实例中使用(因为这些对象都是直接创建的,不是通过BeanDefinition,所以需要这里显式的注册到依赖列表中)。
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    //该对象用来处理实现了ApplicationListener接口的实例,处理在Bean创建完毕的回调中进行注册实例到应用监听列表中,以及在destroy时执行移除操作
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    //这个是实现对LoadTimeWeaverAware接口实现接口注入的处理器
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        // Set a temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }

    //将environment相关的对象注册到对beanFacotry中
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
}

1.4.查看postProcessBeanFactory(beanFactory);的处理细节

这个是给子类预留的一个阶段回调,方便子类在BeanFacotry准备完毕下一个阶段开始之前做一些拓展。
因此在AbstractApplicationContext中未作任何操作

1.5.查看invokeBeanFactoryPostProcessors(beanFactory);的处理细节

这里主要是去调用BeanFactoryPostProcessor中的postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    //执行所有的BeanFactoryPostProcessor
    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()));
    }
}
查看PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())
中的具体执行逻辑
可以看到BeanDefinitionRegistryPostProcessor中的回调是优先于BeanPostProcessor的。
BeanDefinitionRegistryPostProcessor的作用是针对registry注册、修改BeanDefinition用的。
public static void invokeBeanFactoryPostProcessors(
            ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {

    // Invoke BeanDefinitionRegistryPostProcessors first, if any.
    Set processedBeans = new HashSet<>();

    if (beanFactory instanceof BeanDefinitionRegistry) { //BeanFacotry实现了BeanDefinitionRegistry的情况

        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List regularPostProcessors = new LinkedList<>();
        List registryProcessors = new LinkedList<>();
        //这里将通过应用上下文注册的BeanFacotryPostProcessor根据是否是它的子类型BeanDefinitionRegistryPostProcessor划分为两个部分
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                //这里先执行BeanDefinitionRegistryPostProcessor拓展的postProcessBeanDefinitionRegistry回调。
                //由于它是先与postProcessBeanFactory回调进行调用的,因此通过postProcessBeanDefinitionRegistry中注册BeanFactoryPostProcessor的
                //话,是没问题的。
                BeanDefinitionRegistryPostProcessor registryProcessor =
                        (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                registryProcessors.add(registryProcessor);
            }
            else {
                regularPostProcessors.add(postProcessor);
            }
        }

        // Do not initialize FactoryBeans here: We need to leave all regular beans
        // uninitialized to let the bean factory post-processors apply to them!
        // Separate between BeanDefinitionRegistryPostProcessors that implement
        // PriorityOrdered, Ordered, and the rest.
        List currentRegistryProcessors = new ArrayList<>();

        // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
        //由于上面在创建BeanFactory时进行过一次BeanDefinition的加载,因此在BeanFactory中会存在BeanDefinitionRegistryPostProcessor类型的BeanDefinition
        //这里仅仅是获取名称,并未进行实例化
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        //这里把实现了PriorityOrdered的Processor进行优先处理并进行排序
        for (String ppName : postProcessorNames) {
            //这里beanFactory中,由于实例尚未初始化,因此是通过BeanDefinition来判断类型是否匹配的
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        //根据PriorityOrdered进行排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        //未实现排序的追到到后面去
        registryProcessors.addAll(currentRegistryProcessors);
        //这里先执行BeanDefinitionRegistryPostProcessor拓展的postProcessBeanDefinitionRegistry回调。
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();

        // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
        //这里处理实现Ordered的BeanDefinitionRegistryPostProcessors,由于PriorityOrdered先于
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        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();

        // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear
        //循环处理BeanDefinitionRegistryPostProcessors直到没有类型为BeanDefinitionRegistryPostProcessor的为止
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }

        // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
        //调用BeanPostProcessor中的回调
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }

    else {
        // Invoke factory processors registered with the context instance.
        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!
    //处理所有通过BeanDefinitionRegistryPostProcessor注册BeanPostProcessor
    String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    //分组
    List priorityOrderedPostProcessors = new ArrayList<>();
    List orderedPostProcessorNames = new ArrayList<>();
    List nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (processedBeans.contains(ppName)) {
            // skip - already processed in first phase above
        }
        else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    //排序调用
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    List orderedPostProcessors = new ArrayList<>();
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // Finally, invoke all other BeanFactoryPostProcessors.
    List nonOrderedPostProcessors = new ArrayList<>();
    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();
}
可以看到这里BeanFactoryPostProcessors的顺序细节
1.直接注册到AbstractApplicationContext中的beanFactoryPostProcessors且类型为BeanDefinitionRegistryPostProcessor
    执行BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
2.被BeanFactory通过AbstractRefreshableApplicationContext创建BeanFactory时的loadBeanDefinition加载的(或者第一步修改registry注册进去的)类型为
    BeanDefinitionRegistryPostProcessor的而且实现了PriorityOrdered接口的BeanDefinition。然后根据getOrder()的值通过排序器
    ((DefaultListableBeanFactory) beanFactory).getDependencyComparator()如果不存在则用OrderComparator.INSTANCE。
    调用postProcessor.postProcessBeanDefinitionRegistry(registry);
3.被BeanFactory通过AbstractRefreshableApplicationContext创建BeanFactory时的loadBeanDefinition加载的(或者第一步、第二步修改registry注册进去的)类型为
    BeanDefinitionRegistryPostProcessor的而且实现了Ordered接口的BeanDefinition,然后根据getOrder()的值通过排序器
    ((DefaultListableBeanFactory) beanFactory).getDependencyComparator()如果不存在则用OrderComparator.INSTANCE。
    调用postProcessor.postProcessBeanDefinitionRegistry(registry);
    注意:PriorityOrdered是Ordered的子接口,因此这里就算第二部注册了一些实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor,
    仅仅会根据getOrder()值进行排序执行的。
4.到这可能会由3步骤产生新的BeanDefinitionRegistryPostProcessor类型的BeanDefinition,而且每一次调用都可能会产生新的该类型BeanDefinition
    这里直接循环(+ 排序)调用postProcessor.postProcessBeanDefinitionRegistry(registry);,
    直至没有需要处理的BeanDefinitionRegistryPostProcessor类型的为止。
5.执行上面获取的所有BeanPostProcessor中的postProcessor.postProcessBeanFactory(beanFactory);
    虽然BeanDefinitionRegistryPostProcessor为BeanPostProcessor的子类,但是上面处理并没有开始执行postProcessor.postProcessBeanFactory(beanFactory);
    方法,这一步直接全部挨个先调用BeanDefinitionRegistryPostProcessor的postProcessBeanFactory(beanFactory)后调用
    上面从AbstractApplicationContext中获取的类型不为BeanDefinitionRegistryPostProcessor以及1、2、3、4获取的类型为BeanPostProcessor的
    postProcessBeanFactory(beanFactory)回调。
6.在第四步循环处理的是为子类型BeanDefinitionRegistryPostProcessor,因此会产生很多新的BeanPostProcessor这里统一处理有类型为BeanFactoryPostProcessor的
   将所有类型为BeanPostProcessor的根据实现了1、ProrityOrdered接口的与实现2、Ordered接口的以及3、未实现排序接口的分为三组
   然后排序依次执行

1.6.查看registerBeanPostProcessors(beanFactory);处理细节

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
查看PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);代码
public static void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

    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.
    //需要执行是BeanPostProcessor的个数 = 注册到BeanFactory中的个数 + BeanDefinition类型为BeanPostProcessor的个数 + 下面 1 个
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // Separate between BeanPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    //根据PriorityOrdered、Ordered、其他进行分组
    List priorityOrderedPostProcessors = new ArrayList<>();
    List internalPostProcessors = new ArrayList<>();
    List orderedPostProcessorNames = new ArrayList<>();
    List 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);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    //priorityOrdered组排序注册到BeanFactory
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    //ordered组排序注册到BeanFactory
    List orderedPostProcessors = new ArrayList<>();
    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.
    //普通的BeanPostProcessor注册到BeanFactory
    List 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);

    // Finally, re-register all internal BeanPostProcessors.
    //将MergedBeanDefinitionPostProcessor类型的重新注册到靠后的位置
    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).
    //将ApplicationListenerDetector这个processor放到最后面
    //在前面prepareBeanFactory(ConfigurableListableBeanFactory beanFactory)方法中注册过一次,是为了处理BeanFactoryPostProcessor处理过程中可能存在的注册
    //这里重新注册下是为了将这个BeanPostProcessor放到最最后面处理,因为如果可能存在一些通过代理实现监听的对象,包保证它一定能处理到。
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
BeanPostProcessor注册在BeanFacotry中的顺序关系
1.此前直接注册到BeanFactory中的顺序不变
2.BeanPostProcessorChecker紧随此前直接注册到BeanFacotry中BeanPostProcessor
3.实现了PriorityOrdered接口的BeanPostProcessor (根据getOrder()排序)
4.实现了Ordered接口的BeanPostProcessor(根据getOrder()排序)
5.未实现关于Order接口的普通BeanPostProcessor
6.所有类型为BeanPostProcessor的子类型的MergedBeanDefinitionPostProcessor重新注册,使它们的执行顺序在BeanPostProcessor直接类型的后面
7.ApplicationListenerDetector这个BeanPostProcessor放到最最后面执行

1.7.查看initMessageSource();执行细节

MessageSource是spring中对本地化消息的支持
可以通过自定义BeanID为messageSource的方式来自定义 MessageSource 在SpringBoot中是通过autoconfigure中的
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration来定制容器中使用
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration.ResourceBundleCondition作为自动配置下的MessageSource
protected void initMessageSource() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    //这里判断是否定义过BeanID为messageSource的对象
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
        this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
        如果ApplicationContext有父应用上下文对象,那么给messageSource也维护下父级关系
        if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
            HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
            if (hms.getParentMessageSource() == null) {
                // Only set parent context as parent MessageSource if no parent MessageSource
                // registered already.
                hms.setParentMessageSource(getInternalParentMessageSource());
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using MessageSource [" + this.messageSource + "]");
        }
    }
    else {
        // 没有自定义MessageSource的情况下,使用默认委托父级处理的MessageSource(如果没有父级,都进行空处理)
        DelegatingMessageSource dms = new DelegatingMessageSource();
        dms.setParentMessageSource(getInternalParentMessageSource());
        this.messageSource = dms;
        // 注册到Bean容器中 以便在应用上下文环境中 使用依赖注入、接口注入等方式获取当前MessageSource
        beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
                    "': using default [" + this.messageSource + "]");
        }
    }
}

1.8.查看initApplicationEventMulticaster();执行细节

这里主要配置应用上下文中的ApplicationEvent的事件广播实现类对象,来处理容器中的事件分发工作。
实现方式与上面MessageSource类似,如果没有自定义的bean选用默认的
protected void initApplicationEventMulticaster() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster =
                beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isDebugEnabled()) {
            logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    else {
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                    APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                    "': using default [" + this.applicationEventMulticaster + "]");
        }
    }
}

1.9.查看onRefresh();

改方法在AbstractApplicationContext层 未作任何实现,是为子类留的一个回调。方便子类在容器中基本准备完毕时进行拓展自己的行为。
比如web容器是在这里开始创建web服务对象,以及一些初始化工作。

1.10.查看registerListeners();实现

这里主要是实现将,应用上下文事件监听对象的注册。
protected void registerListeners() {
    // 注册直接设置到容器中的监听实现类对象(在容器事件发布器未初始化时执行addApplicationListener的对象会设置到这里)
    for (ApplicationListener listener : getApplicationListeners()) {
        getApplicationEventMulticaster().addApplicationListener(listener);
    }

    // 对于其他对象 由于还没有开始初始化执行对应的BeanPostProcessor 这里只是注册进去一个BeanName
    String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    for (String listenerBeanName : listenerBeanNames) {
        getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    }

    // 对于ApplicationEventMulticaster尚未初始化前发布的一些事件 会缓存到earlyApplicationEvents中,在这里执行事件分发
    Set earlyEventsToProcess = this.earlyApplicationEvents;
    this.earlyApplicationEvents = null;
    if (earlyEventsToProcess != null) {
        for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
            getApplicationEventMulticaster().multicastEvent(earlyEvent);
        }
    }
}

1.11.查看finishBeanFactoryInitialization(beanFactory);实现

这一步是将无需懒加载的单例对象都进行初始化
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // 初始化一个ConversionService,它的作用类似于JavaBean中的PropertyEditor用来转换配置值
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
            beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
        beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
    }

    // Register a default embedded value resolver if no bean post-processor
    // (such as a PropertyPlaceholderConfigurer bean) registered any before:
    // at this point, primarily for resolution in annotation attribute values.
    // 如果不存在value解析器,添加一个基于environment的占位符解析器
    if (!beanFactory.hasEmbeddedValueResolver()) {
        beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

    // Stop using the temporary ClassLoader for type matching.
    beanFactory.setTempClassLoader(null);

    // Allow for caching all bean definition metadata, not expecting further changes.
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    // 这里开始进行单例对象实例化工作。 后面详细查看创建单例对象的实现细节。
    beanFactory.preInstantiateSingletons();
}

1.12.finishRefresh();

这里应用上下文 已经准备完毕,主要负责事件发布,以及与处理应用上下文Lifecycle的实现
protected void finishRefresh() {
    // Clear context-level resource caches (such as ASM metadata from scanning).
    clearResourceCaches();

    // Initialize lifecycle processor for this context.
    //这里初始化一个Lifecycle的处理器,与MessageSource类似,如果不指定Bean ID 为lifecycleProcessor的对象,那么会选用一个默认的处理器
    initLifecycleProcessor();

    // Propagate refresh to lifecycle processor first.
    //这里是启动是实现SmartLifecycle且isAutoStartup()返回true的对象,如果其他的对象想执行start()必须进行手动调用applicationContext.start()
    getLifecycleProcessor().onRefresh();

    // Publish the final event.
    //发布容器初始化完成的事件
    publishEvent(new ContextRefreshedEvent(this));

    // Participate in LiveBeansView MBean, if active.
    // 这里是对于容器实现的一个json视图
    LiveBeansView.registerApplicationContext(this);
}

你可能感兴趣的:(spring,源码学习,java)