0


Spring源码深度解析

一、初始化化上下文

1.1、初识GenericApplicationContext,容器的启动

 该类为spring对外提供的可扩展的上下文,该类完成了Spring的几乎所有功能,该类为spring对外提供的框架入口类;用户可通过继承该类,调用register方法,向Spring中注册用户自定义的Bean或配置类,注册好后用户需要通过AnnotationConfigUtils工具类提供的registerAnnotationConfigProcessors方法向容器中注册Spring的BeanPostProcessor及其子接口(Spring对外提供可扩展的前置后置处理器,在制造bean的生命周期的不同时间段进行回调),BeanFactoryPostProcessor(spring对外提供的可扩展的对beanFactory的前置后置处理器主要用于解析配置类,向beanFactory中注册BeanDefinition,以及递归解析配置类),其中bean的前置后置处理器完成了对bean的动态代理,属性注入,注解方式的生命周期的回调等后面做详细介绍;如果不进行此步骤用户也可自定义BeanPostProcessor,BeanFactoryPostProcessor完成用户想要的相关功能;SpringBoot是继承GenericApplicationContext类向容器中注册配置类监听器等实现容器的初始化话;基本上都是先注册用户自定义的bean或配置,然后让Spring自身做持续解析,完成项目初始化;

spring初始化

例1: 通过GenericApplicationContext初始化

        GenericApplicationContext context = new GenericApplicationContext();
        //注册beanPostProcess,BeanFactoryPostPorcess
        AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
        //可通过此方法或此方法的重载方法对普通类或配置类进行解析并建模,并向BeanFactory注册解析好的beanDefinition
        context.registerBean(Config.class);
        // 初始化,刷新容器,解析配置类,注册通过配置类扫描符合条件的类并封装成beanDefinition,        
        // 对容器内的beanDefinition做解析,生成bean等
        context.refresh();
        Demo bean = context.getBean(Demo.class);

例2:通过Spring提供的实现类进行初始化

        //该类的构造方法完成了beanPostprocess和beanFactoryPostprocess的注册和刷新容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        Demo bean = context.getBean(Demo.class);

GenericApplicationContext的类结构

1.2 refresh方法

该方法位于AbstractApplicationContext实现,为ConfigurableApplicationContext接口提供的方法,该ConfigurableApplicationContext类的主要功能为

摘自类的注释:

大多数(如果不是所有)应用程序上下文都将实现 SPI 接口。除了 ApplicationContext 接口中的应用程序上下文客户端方法之外,还提供了配置应用程序上下文的工具。配置和生命周期方法被封装在这里,以避免使它们对 ApplicationContext 客户端代码显而易见。本方法只应由启动和关闭代码使用

refresh方法的功能为

加载或持续解析配置,完成容器的初始化,加载失败的时候销毁已经创建的单例,以避免资源悬空。此方法相当于容器的初始化核心方法,可见此方法的重要性,读懂此方法spring就读懂了

下面对refresh方法做解读

    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // 对容器刷新前的准备,设置容器的状态,环境Environment的准备,早期事件earlyApplicationListeners,监听器earlyApplicationEvents的处理.
            prepareRefresh();

            // 1.刷新bean工厂 子类可通过重写refreshBeanFactory方法向容器中注入配置交给后续步骤做持续化解析
            // 2.为bean工厂设置名称
            // 3.获取bean工厂
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // 准备bean工厂
            prepareBeanFactory(beanFactory);

            try {
                //允许在此处注册调用子类实现的postProcessBeanFactory方法向容器中注册beanPostProcess或BeanFactoryPostProcess
                //提过的子类扩展方法,spring-boot有使用到此方法注册WebApplicationContextServletContextAwareProcessor等
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                // org.springframework.context.annotation.ConfigurationClassPostProcessor
                // org.springframework.context.annotation.ConfigurationClassParser
                // 注册扫描所有的bean描述和定义 处理配置类 import注解等处理 代理配置类@Configuration重要
                invokeBeanFactoryPostProcessors(beanFactory);

                // 注册beanPostProcess
                registerBeanPostProcessors(beanFactory);

                // 国际化
                initMessageSource();

                // 初始化多播器
                initApplicationEventMulticaster();

                // 在子类中初始化特殊的bean spring-boot有使用该方法创建webServer
                onRefresh();

                // 从容器中获取监听器并注册
                registerListeners();

                // 实例化所有为实例化的单例bean
                finishBeanFactoryInitialization(beanFactory);

                // 调用bean的生命周期回调函数,发布容器初始化完成事件
                finishRefresh();
            }

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

                // 创建失败销毁容器中的所有单例bean释放资源
                destroyBeans();

                // 设置容器状态为关闭状态
                cancelRefresh(ex);
                
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                // 清空创建过程中的缓存
                resetCommonCaches();
            }
        }
    }

下面对invokeBeanFactoryPostProcessors(beanFactory)方法做解读

我们直接进入其委托执行的方法PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())方法。

该方法主要用于:

1.按顺序执行BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry并做持续递归解析执行(当解析注册配置类中含有BeanDefinitionRegistryPostProcessor时会循环解析并调用postProcessBeanDefinitionRegistry方法)。

2.按顺序执行BeanFactoryPostProcessor.postProcessBeanFactory。

    /**
     * 
     * 该方法主要用于
     * 1.按顺序执行BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry并做递归解析执行
     * 2.按顺序执行BeanFactoryPostProcessor.postProcessBeanFactory
     * 
     * @param beanFactory bean工厂 
     * @param beanFactoryPostProcessors 回调方法
     */
    public static void invokeBeanFactoryPostProcessors(
            ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

        // Invoke BeanDefinitionRegistryPostProcessors first, if any.
        //如果有的话,首先调用
        Set<String> processedBeans = new HashSet<>();
        //若果类型是BeanDefinitionRegistry
        if (beanFactory instanceof BeanDefinitionRegistry) {
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            //存储提取的常规BeanFactoryPostProcessor
            List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
            //存储提取的BeanDefinitionRegistryPostProcessor
            List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                //
                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                    BeanDefinitionRegistryPostProcessor registryProcessor =
                            (BeanDefinitionRegistryPostProcessor) postProcessor;
                    //将BeanDefinitionRegistryPostProcessor添加到registryProcessor
                    registryProcessor.postProcessBeanDefinitionRegistry(registry);
                    //添加到regularPostProcessors
                    registryProcessors.add(registryProcessor);
                } else {
                    //添加到regularPostProcessors
                    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.
            //不在此处初始化 FactoryBeans:我们需要让所有常规 bean 保持未初始化状态,
            // 以便 bean 工厂后处理器应用到它们!
            // 将实现 PriorityOrdered、Ordered 和其余部分的 BeanDefinitionRegistryPostProcessor 分开。
            List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

            // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            // 首先,调用实现 PriorityOrdered 的 BeanDefinitionRegistryPostProcessor。

            //获取所有实现了BeanDefinitionRegistryPostProcessor的beanName
            String[] postProcessorNames =
                    beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

            //提取实现了PriorityOrdered的beanName,
            // 添加到当前处理的list中,
            // 添加到processedBeans中
            for (String ppName : postProcessorNames) {
                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }

            //对当前currentRegistryProcessors进行排序
            sortPostProcessors(currentRegistryProcessors, beanFactory);

            //添加到registryProcessors中
            registryProcessors.addAll(currentRegistryProcessors);
            //执行当前批次的BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry方法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            //清空当前执行批次
            currentRegistryProcessors.clear();

            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
            //提取所有BeanDefinitionRegistryPostProcessor类型的beanName
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            //提取实现了Ordered接口单未处理的BeanName添加到当前处理的批次内进行处理
            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
            registryProcessors.addAll(currentRegistryProcessors);
            //执行postProcessor.postProcessBeanDefinitionRegistry方法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            //清空当前执行的的批次
            currentRegistryProcessors.clear();

            // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            // 递归解析BeanDefinitionRegistryPostProcessor,调用postProcessor.postProcessBeanDefinitionRegistry
            // 可能会解析出新的BeanDefinitionRegistryPostProcessor,解析出新的就继续执行postProcessor.postProcessBeanDefinitionRegistry
            // 直到全部解析完成,在此处优先级会失效在解析importSelector使用的同样的解析思路递归解析
            boolean reiterate = true;
            while (reiterate) {
                reiterate = false;
                //获取BeanDefinitionRegistryPostProcessor
                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);
                //将当前批次添加到currentRegistryProcessors方便后续排除已解析的
                registryProcessors.addAll(currentRegistryProcessors);
                //执行
                invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
                //清空当前批次,进行下一批次
                currentRegistryProcessors.clear();
            }

            // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
            //执行所有的postProcessor.postProcessBeanFactory,bean工厂回调方法
            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!
        // 不要在此处初始化 FactoryBeans:我们需要让所有常规 bean 保持未初始化状态,
        // 以便 bean 工厂后处理器应用到它们!
        // 获取所有的BeanFactoryPostProcessor
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

        // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
        // Ordered, and the rest.
        //存储提取的实现了PriorityOrdered的BeanFactoryPostProcessor
        List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        //存储提取的实现了Ordered的BeanFactoryPostProcessor
        List<String> orderedPostProcessorNames = new ArrayList<>();
        //存储普通的
        List<String> 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.
        //对priorityOrderedPostProcessors进行排序
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        //执行postProcessor.postProcessBeanFactory
        invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

        // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
        List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
        for (String postProcessorName : orderedPostProcessorNames) {
            orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        }
        //对orderedPostProcessors进行排序
        sortPostProcessors(orderedPostProcessors, beanFactory);
        //执行postProcessor.postProcessBeanFactory
        invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

        //按相同步骤执行普通的BeanFactoryPostProcessor
        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...
        //清除缓存的合并 bean 定义,因为后处理器可能已经修改了原始元数据,例如替换值中的占位符...
        beanFactory.clearMetadataCache();
    }

下面对BeanDefinitionRegistryPostProcessor核心实现类配置解析类ConfigurationClassPostProcessor做解读

该类主要用于使用ConfigurationClassParser递归对bean进行解析,解析注解Component,PropertySources、ComponentScans、ComponentScan、ImportResource、Import、ImportSelector、DeferredImportSelector等

下面对org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions做解读

该方法用于:

1.提取配置类以及普通的bean。

2.然后对提取出的beanDefinition进行排序。

3.获取或创建bean的名字生成器BeanNameGenerator。

4.获取或创建环境environment。

5.构建ConfigurationClassParser用于解析配置类。

6.通过ConfigurationClassParser.parse方法循环递进解析配置bean。

7.将解析出来的配置类通过加载进入BeanDefinitionRegistry中

org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader#loadBeanDefinitions

    /**
     * Build and validate a configuration model based on the registry of
     * 解析配置类并肩解析出的配置类封装成beanDefinition注册进入DefaultListableBeanFactory中
     * {@link Configuration} classes.
     */
    public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
        List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
        String[] candidateNames = registry.getBeanDefinitionNames();

        //提取需要解析的beanName
        for (String beanName : candidateNames) {
            BeanDefinition beanDef = registry.getBeanDefinition(beanName);
            if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
                }
            }
            else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
                configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
            }
        }

        // Return immediately if no @Configuration classes were found
        if (configCandidates.isEmpty()) {
            return;
        }

        // 按Order对beanName进行排序
        configCandidates.sort((bd1, bd2) -> {
            int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
            int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
            return Integer.compare(i1, i2);
        });

        // Detect any custom bean name generation strategy supplied through the enclosing application context
        //检测通过封闭应用程序上下文提供的任何自定义 bean 名称生成策略
        SingletonBeanRegistry sbr = null;
        if (registry instanceof SingletonBeanRegistry) {
            sbr = (SingletonBeanRegistry) registry;
            if (!this.localBeanNameGeneratorSet) {
                BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
                        AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
                if (generator != null) {
                    this.componentScanBeanNameGenerator = generator;
                    this.importBeanNameGenerator = generator;
                }
            }
        }

        if (this.environment == null) {
            this.environment = new StandardEnvironment();
        }

        // Parse each @Configuration class 解析每个 @Configuration 类
        //构建解析配置的类
        ConfigurationClassParser parser = new ConfigurationClassParser(
                this.metadataReaderFactory, this.problemReporter, this.environment,
                this.resourceLoader, this.componentScanBeanNameGenerator, registry);
        //存储即将解析这一批次bean,解析完后清空,在存储从这一批次中解析出的bean,继续解析直至全部解析完毕
        Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
        Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
        do {
            //解析配置bean
            parser.parse(candidates);
            //校验
            parser.validate();
            //获取解析好的配置类
            Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
            //移除已经加载过的BeanDefinition
            configClasses.removeAll(alreadyParsed);

            // Read the model and create bean definitions based on its content
            // 读取模型并根据其内容创建 bean 定义
            if (this.reader == null) {
                this.reader = new ConfigurationClassBeanDefinitionReader(
                        registry, this.sourceExtractor, this.resourceLoader, this.environment,
                        this.importBeanNameGenerator, parser.getImportRegistry());
            }
            //1.从自身导入BeanDefinition到BeanDefinitionRegistry
            //2.从@Bean方法中导入BeanDefinitionRegistry
            //3.从@ImportResource注解配置类导入的资源文件导入BeanDefinition到BeanDefinitionRegistry
            this.reader.loadBeanDefinitions(configClasses);
            //添加到alreadyParsed中
            alreadyParsed.addAll(configClasses);
            //清空当前解析批次用于存储下一解析批次
            candidates.clear();
            
            //如果registry中bean的定义的数量大于candidateNames提取为解析的bean定义进行下一批次解析
            if (registry.getBeanDefinitionCount() > candidateNames.length) {
                //获取所有bean的名字
                String[] newCandidateNames = registry.getBeanDefinitionNames();
                //将上一轮作为旧的已解析beanName用于排除已解析的BeanName
                Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
                //存放本轮已解析BeanName
                Set<String> alreadyParsedClasses = new HashSet<>();
                for (ConfigurationClass configurationClass : alreadyParsed) {
                    alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
                }
                //通过上一次所有bean名字和本轮已解析的beanName和容器中所有BeanName提取出下一轮需要解析的BeanName,用于继续解析
                for (String candidateName : newCandidateNames) {
                    if (!oldCandidateNames.contains(candidateName)) {
                        BeanDefinition bd = registry.getBeanDefinition(candidateName);
                        if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
                                !alreadyParsedClasses.contains(bd.getBeanClassName())) {
                            candidates.add(new BeanDefinitionHolder(bd, candidateName));
                        }
                    }
                }
                candidateNames = newCandidateNames;
            }
        }
        //如果candidates需要下一轮解析的beanName为空结束循环
        while (!candidates.isEmpty());

        // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
        // 将ImportRegistry当成一个bean注册进行注册以支持ImportAware接口的@Configuration配置类
        if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
            sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
        }

        if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
            // Clear cache in externally provided MetadataReaderFactory; this is a no-op
            // for a shared cache since it'll be cleared by the ApplicationContext.
            //清除外部提供的 MetadataReaderFactory 中的缓存;这是共享缓存的无操作,因为它将被 ApplicationContext 清除。
            ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
        }
    }

下面对ConfigurationClassParser.parse做解读,Spring中干活的一般都是以do开头的我们直接跟进doProcessConfigurationClass方法做解读

该方法完成了解析注解Component,PropertySources、ComponentScans、ComponentScan、ImportResource、Import、ImportSelector、DeferredImportSelector等

    /**
     * Apply processing and build a complete {@link ConfigurationClass} by reading the
     * annotations, members and methods from the source class. This method can be called
     * multiple times as relevant sources are discovered.
     * 通过从类中获取注解,内部类,方法将其解析封装成ConfigurationClass
     * @param configClass the configuration class being build
     * @param sourceClass a source class
     * @return the superclass, or {@code null} if none found or previously processed
     */
    @Nullable
    protected final SourceClass doProcessConfigurationClass(
            ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
            throws IOException {

        if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
            // Recursively process any member (nested) classes first
            // 循环(递归)处理内部类配置 processConfigurationClass()
            processMemberClasses(configClass, sourceClass, filter);
        }

        // Process any @PropertySource annotations
        // 处理@PropertySource
        for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), PropertySources.class,
                org.springframework.context.annotation.PropertySource.class)) {
            if (this.environment instanceof ConfigurableEnvironment) {
                processPropertySource(propertySource);
            }
            else {
                logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
                        "]. Reason: Environment must implement ConfigurableEnvironment");
            }
        }

        // Process any @ComponentScan annotations
        // 处理@ComponentScans @ComponentScan注解
        Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
        if (!componentScans.isEmpty() &&
                !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
            for (AnnotationAttributes componentScan : componentScans) {
                // The config class is annotated with @ComponentScan -> perform the scan immediately
                Set<BeanDefinitionHolder> scannedBeanDefinitions =
                        this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
                // Check the set of scanned definitions for any further config classes and parse recursively if needed
                for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
                    BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
                    if (bdCand == null) {
                        bdCand = holder.getBeanDefinition();
                    }
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
                        parse(bdCand.getBeanClassName(), holder.getBeanName());
                    }
                }
            }
        }

        // Process any @Import annotations
        //处理@Import注解
        processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

        // Process any @ImportResource annotations
        // 处理  @ImportResource 注解
        AnnotationAttributes importResource =
                AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
        if (importResource != null) {
            String[] resources = importResource.getStringArray("locations");
            Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
            for (String resource : resources) {
                String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
                configClass.addImportedResource(resolvedResource, readerClass);
            }
        }

        // Process individual @Bean methods
        // 处理 @Bean 方法
        Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
        for (MethodMetadata methodMetadata : beanMethods) {
            configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
        }

        // Process default methods on interfaces
        // 递归处理接口上的@Bean方法
        processInterfaces(configClass, sourceClass);

        // Process superclass, if any
        // 处理父类
        if (sourceClass.getMetadata().hasSuperClass()) {
            String superclass = sourceClass.getMetadata().getSuperClassName();
            if (superclass != null && !superclass.startsWith("java") &&
                    !this.knownSuperclasses.containsKey(superclass)) {
                this.knownSuperclasses.put(superclass, configClass);
                // Superclass found, return its annotation metadata and recurse
                return sourceClass.getSuperClass();
            }
        }

        // No superclass -> processing is complete
        return null;
    }

下面对ComponentScan注解的解析方法ComponentScanAnnotationParser.parse做解读

    /**
     * 此方法用于解析componentScan注解,并扫描对应的包,本方法主要功能为构建bean的扫描器ClassPathBeanDefinitionScanner
     *
     * @param componentScan
     * @param declaringClass
     * @return
     */
    public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, String declaringClass) {
        //创建basePackages扫描器用渝扫描包并将构建号的BeanDefinition注册进入BeanDefinitionRegistry中
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(
                this.registry,
                componentScan.getBoolean("useDefaultFilters"),
                this.environment,
                this.resourceLoader
        );
        //获取自定义beanName生成器
        Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
        boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
        //设置beanName生成器
        scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
                BeanUtils.instantiateClass(generatorClass));
        //后去bean的代理方式
        ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
        if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
            //非默认代理方式
            scanner.setScopedProxyMode(scopedProxyMode);
        } else {
            //获取自定义的ScopeMetadataResolver并设置进入scanner
            Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
            scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
        }
        //设置资源匹配正则
        scanner.setResourcePattern(componentScan.getString("resourcePattern"));

        //获取自定义includeFilters用去筛选需要注册的Bean,用户可自定义赛选条件完成自定义类的注入
        //useDefaultFilters 要设置成false mybatis-plus在构建ClassPathMapperScanner时通过此方式
        //结合factoryBean完成mapper的注册
        for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
            for (TypeFilter typeFilter : typeFiltersFor(filter)) {
                scanner.addIncludeFilter(typeFilter);
            }
        }
        //获取排除bean的excludeFilters
        for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
            for (TypeFilter typeFilter : typeFiltersFor(filter)) {
                scanner.addExcludeFilter(typeFilter);
            }
        }
        //是否懒加载
        boolean lazyInit = componentScan.getBoolean("lazyInit");
        if (lazyInit) {
            scanner.getBeanDefinitionDefaults().setLazyInit(true);
        }
        //提取basePackages
        Set<String> basePackages = new LinkedHashSet<>();
        String[] basePackagesArray = componentScan.getStringArray("basePackages");
        for (String pkg : basePackagesArray) {
            String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
            Collections.addAll(basePackages, tokenized);
        }
        for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
            basePackages.add(ClassUtils.getPackageName(clazz));
        }
        if (basePackages.isEmpty()) {
            basePackages.add(ClassUtils.getPackageName(declaringClass));
        }
        //排除当前配置bean
        scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
            @Override
            protected boolean matchClassName(String className) {
                return declaringClass.equals(className);
            }
        });
        //执行扫描
        return scanner.doScan(StringUtils.toStringArray(basePackages));
    }

下面对ClassPathBeanDefinitionScanner.doScan做解读

该方法主要通过在购键该类的过程中设置的条件对符合条件的Bean进行建模封装成BeanDefinition注册进入BeanDefinitionRegistry中

我们进入doScan方法

    /**
     * Perform a scan within the specified base packages,
     * returning the registered bean definitions.
     * <p>This method does <i>not</i> register an annotation config processor
     * but rather leaves this up to the caller.
     * 扫描出所有符合条件的bean并对其解析建模封装成beanDefinition注册进入BeanDefinitionRegistry中
     *
     * @param basePackages the packages to check for annotated classes
     * @return set of beans registered if any for tooling registration purposes (never {@code null})
     */
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Assert.notEmpty(basePackages, "At least one base package must be specified");
        Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
        for (String basePackage : basePackages) {
            //扫描出所有符合条件的bean并对其解析建模封装成beanDefinition
            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
            for (BeanDefinition candidate : candidates) {
                //解析bean的Scope
                ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
                candidate.setScope(scopeMetadata.getScopeName());
                //生成bean的名字
                String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
                if (candidate instanceof AbstractBeanDefinition) {
                    postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
                }
                if (candidate instanceof AnnotatedBeanDefinition) {
                    //解析bean注解@Lazy,@Primary,@DependsOn,@Role,@Description并设置进入AnnotatedBeanDefinition中
                    AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
                }
                //检查注册是否与现有bean冲突,不冲突则注册,冲突抛出异常
                if (checkCandidate(beanName, candidate)) {
                    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
                    //处理bean的代理信息
                    definitionHolder =
                            AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
                    beanDefinitions.add(definitionHolder);
                    //注册进入BeanDefinitionRegistry
                    registerBeanDefinition(definitionHolder, this.registry);
                }
            }
        }
        return beanDefinitions;
    }

下面我们对扫描bean的方法findCandidateComponents做解读

该方法完成Bean的扫描筛选,首先将扫描包下面所有的类资源封装成Resource

    /**
     * 扫描包路径下的所有资源,封装成BeanDefinition,赛选出符合条件的BeanDefinition返回
     * @param basePackage
     * @return
     */
    private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
        Set<BeanDefinition> candidates = new LinkedHashSet<>();
        try {
            String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    resolveBasePackage(basePackage) + '/' + this.resourcePattern;
            //获取包下面的所有资源
            Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
            boolean traceEnabled = logger.isTraceEnabled();
            boolean debugEnabled = logger.isDebugEnabled();
            for (Resource resource : resources) {
                if (traceEnabled) {
                    logger.trace("Scanning " + resource);
                }
                try {
                    //将资源封装成SimpleMetadataReader方便解析
                    MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
                    //根据条件赛选
                    if (isCandidateComponent(metadataReader)) {
                        //封装成ScannedGenericBeanDefinition
                        ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                        //设置资源
                        sbd.setSource(resource);
                        //确定给定的 bean 定义是否有资格作为候选。根据类文件元数据筛选,扫描顶层具体类或者虽然是抽象类但是存在@Lookup标记的方法
                        if (isCandidateComponent(sbd)) {
                            if (debugEnabled) {
                                logger.debug("Identified candidate component class: " + resource);
                            }
                            //添加到candidates
                            candidates.add(sbd);
                        }
                        else {
                            if (debugEnabled) {
                                logger.debug("Ignored because not a concrete top-level class: " + resource);
                            }
                        }
                    }
                    else {
                        if (traceEnabled) {
                            logger.trace("Ignored because not matching any filter: " + resource);
                        }
                    }
                }
                catch (FileNotFoundException ex) {
                    if (traceEnabled) {
                        logger.trace("Ignored non-readable " + resource + ": " + ex.getMessage());
                    }
                }
                catch (Throwable ex) {
                    throw new BeanDefinitionStoreException(
                            "Failed to read candidate component class: " + resource, ex);
                }
            }
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
        }
        //返回符合条件的candidates
        return candidates;
    }

注:用户在扩展是通常继承ClassPathBeanDefinitionScanner类,自定义赛选条件,重写doScan方法 调用父类doScan方法扫描注册BeanDefinition,返回扫描注册后的BeanDefinition,然后对其做处理,完成自己的逻辑,将扫描出的符合条件的BeanDefinition做处理后

例如Mybatis的@MapperScan注解:

public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

    if (beanDefinitions.isEmpty()) {
      LOGGER.warn(() -> "No MyBatis mapper was found in '" + Arrays.toString(basePackages)
          + "' package. Please check your configuration.");
    } else {
      processBeanDefinitions(beanDefinitions);
    }

    return beanDefinitions;
  }

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
    GenericBeanDefinition definition;
    for (BeanDefinitionHolder holder : beanDefinitions) {
      definition = (GenericBeanDefinition) holder.getBeanDefinition();
      String beanClassName = definition.getBeanClassName();
      LOGGER.debug(() -> "Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + beanClassName
          + "' mapperInterface");

      // the mapper interface is the original class of the bean
      // but, the actual class of the bean is MapperFactoryBean
      definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
      definition.setBeanClass(this.mapperFactoryBeanClass);

      definition.getPropertyValues().add("addToConfig", this.addToConfig);

      boolean explicitFactoryUsed = false;
      if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
        definition.getPropertyValues().add("sqlSessionFactory",
            new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
        explicitFactoryUsed = true;
      } else if (this.sqlSessionFactory != null) {
        definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
        explicitFactoryUsed = true;
      }

      if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
        if (explicitFactoryUsed) {
          LOGGER.warn(
              () -> "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
        }
        definition.getPropertyValues().add("sqlSessionTemplate",
            new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
        explicitFactoryUsed = true;
      } else if (this.sqlSessionTemplate != null) {
        if (explicitFactoryUsed) {
          LOGGER.warn(
              () -> "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
        }
        definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
        explicitFactoryUsed = true;
      }

      if (!explicitFactoryUsed) {
        LOGGER.debug(() -> "Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
      }
      definition.setLazyInit(lazyInitialization);
    }
  }

致此Spring对所有类的扫描建模,注册进入BeanDefinitionRegistry完成

下面对ConfigurationClassParser.processImports方法做注释

该方法主要用于处理@import注解的ImportSelector,DeferredImportSelector,ImportBeanDefinitionRegistrar以及导入的普通类

Spring在解析DeferredImportSelector是先将其封装成DeferredImportSelectorHolder,然后存入DeferredImportSelectorHandler.deferredImportSelectors中,在ConfigurationClassParser.parse方法中调用deferredImportSelectorHandler.process进行处理,先创建DeferredImportSelectorGroupingHandler对象,对deferredImportSelectors进行排序,然后注册进入DeferredImportSelectorGroupingHandler中,调用deferredImportSelector.process方法,然后调用ImportSelector.selectImports方法然后将返回的对象遍历,调用processImports方法对返回的每一个对象进行解析

注:

1.spring在解析ImportSelector时是有序的,但前提,不是由ImportSelector的selectImports方法引入ImportSelector,在解析过程中调用DeferredImportSelectorHandler.process时也就是处理添加到holder中是会见deferredImportSelectors置空,知道首层批次解析完成才会new一个List,而在添加到DeferredImportSelectorHandler.deferredImportSelectors过程中会判断deferredImportSelectors是否为空,若为空直接处理,这样设计的原因可能是因为在嵌套@import注解可能顺序与父@import无关

2.当解析完后回到ConfigurationClassPostProcessor#processConfigBeanDefinitions

中,再次将新注册进入BeanDefinitionRegistry的beanDefinition获取出来排除已解析的,进行解析

解析大体思路有点像前面解析beanFactoryProcess以及配置类持续深入递归解析

    /**
     * 对@import注解做解析
     *
     * @param configClass             配置类
     * @param currentSourceClass
     * @param importCandidates
     * @param exclusionFilter
     * @param checkForCircularImports
     */
    private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
                                Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
                                boolean checkForCircularImports) {

        if (importCandidates.isEmpty()) {
            return;
        }

        //对循环引用做校验
        if (checkForCircularImports && isChainedImportOnStack(configClass)) {
            this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
        } else {
            //添加到栈中
            this.importStack.push(configClass);
            try {
                for (SourceClass candidate : importCandidates) {
                    //对ImportSelector做处理
                    if (candidate.isAssignable(ImportSelector.class)) {
                        // Candidate class is an ImportSelector -> delegate to it to determine imports
                        //加载ImportSelector类
                        Class<?> candidateClass = candidate.loadClass();
                        //实例化ImportSelector类,
                        // 1.构造函数实例化只支持environment, resourceLoader, registry, classLoader作为参数
                        // 2.调用Aware接口
                        ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
                                this.environment, this.resourceLoader, this.registry);
                        //获取排除条件
                        Predicate<String> selectorFilter = selector.getExclusionFilter();
                        if (selectorFilter != null) {
                            exclusionFilter = exclusionFilter.or(selectorFilter);
                        }
                        //处理DeferredImportSelector类
                        if (selector instanceof DeferredImportSelector) {
                            //将DeferredImportSelector添加到deferredImportSelectorHandler中然后调用process ->processGroupImports
                            // 对于DeferredImportSelector
                            this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
                        }
                        //处理ImportSelector类
                        else {
                            String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
                            Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
                            processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
                        }
                    }
                    //将ImportBeanDefinitionRegistrar添加进入ConfigurationClass中在
                    // org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass
                    // 中处理org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars
                    else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
                        // Candidate class is an ImportBeanDefinitionRegistrar ->
                        // delegate to it to register additional bean definitions
                        Class<?> candidateClass = candidate.loadClass();
                        //实例化
                        ImportBeanDefinitionRegistrar registrar =
                                ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
                                        this.environment, this.resourceLoader, this.registry);
                        //添加进入configClass中
                        configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
                    } else {
                        // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
                        // process it as an @Configuration class
                        this.importStack.registerImport(
                                currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
                        //处理由ImportSelector 或DeferredImportSelector导入的类 有点绕
                        processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
                    }
                }
            } catch (BeanDefinitionStoreException ex) {
                throw ex;
            } catch (Throwable ex) {
                throw new BeanDefinitionStoreException(
                        "Failed to process import candidates for configuration class [" +
                                configClass.getMetadata().getClassName() + "]", ex);
            } finally {
                //从处理栈中移除
                this.importStack.pop();
            }
        }
    }

致此配置bean初步解析完成接下来我们回到org.springframework.context.annotation.ConfigurationClassPostProcessor#

postProcessBeanFactory中该方法主要用于对加了@Configuration注解的类进行代理,代理原因为添加了@Bean注解的方法,被直接调用的时候不会重Spring容器中获取二是直接返回,会导致本应是单例的出现多例,而直接获取的类未经spring DI处理,未经历一个bean本应经历的完整的生命周期。所以要对其进行代理,但是如果在本类中直接调用方法同样也会造成bean未经历完整的生命周期

致此我们完成了对refresh方的invokeBeanFactoryPostProcessors

下面我们对registerBeanPostProcessors做解析

该方法主要用于向容器中注入beanPostProcess子类和继承后向容器注入自定义beanPostProcess,大概就是通过委托PostProcessorRegistrationDelegate.registerBeanPostProcessors方法注册,接下来refresh防范就是处理国际化信息,初始化多播器,注册监听器,初始化所用bean等

    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.
        // 注册 BeanPostProcessorChecker,
        // 它会在 BeanPostProcessor 实例化期间创建 bean 时记录一条信息消息,
        // 即当 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.
        //将实现 PriorityOrdered、Ordered 和其余部分的 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);
                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 的 BeanPostProcessor。
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

        // Next, register the BeanPostProcessors that implement Ordered.
        //接下来,注册实现 Ordered 的 BeanPostProcessor
        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.
        //注册所有常规的 BeanPostProcessor。
        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.
        // 最后,重新注册所有内部 BeanPostProcessor。
        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).
        // 重新注册用于将内部 bean 检测为 ApplicationListeners 的后处理器,
        // 将其移动到处理器链的末尾(用于拾取代理等)
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }

接下来我们对registerListeners做注释

protected void registerListeners() {
        // Register statically specified listeners first.
        // 首先注册静态指定的监听器。
        for (ApplicationListener<?> listener : getApplicationListeners()) {
            getApplicationEventMulticaster().addApplicationListener(listener);
        }

        // Do not initialize FactoryBeans here: We need to leave all regular beans
        // uninitialized to let post-processors apply to them!
        // 翻译:不要在这里初始化 FactoryBeans:我们需要让所有常规 bean 保持未初始化状态,以让后处理器应用于它们!
        String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
        for (String listenerBeanName : listenerBeanNames) {
            getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
        }

        // Publish early application events now that we finally have a multicaster...
        // 翻译:发布早期应用程序事件,因为我们终于有了一个多播器......
        Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
        this.earlyApplicationEvents = null;
        if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
            for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
                getApplicationEventMulticaster().multicastEvent(earlyEvent);
            }
        }
    }

接下对refresh.finishBeanFactoryInitialization方法做解析

该方法主要用于实例化容器中所有未实例化的bean,根据前面对bean的定义,进行实例化,让bean经历完整的生命周期

1.BeanNameAware's setBeanName
2.BeanClassLoaderAware's setBeanClassLoader
3.BeanFactoryAware's setBeanFactory
4.EnvironmentAware's setEnvironment
5.EmbeddedValueResolverAware's setEmbeddedValueResolver
6.ResourceLoaderAware's setResourceLoader (only applicable when running in an application context)
7.ApplicationEventPublisherAware's setApplicationEventPublisher (only applicable when running in an application context)
8.MessageSourceAware's setMessageSource (only applicable when running in an application context)
9.ApplicationContextAware's setApplicationContext (only applicable when running in an application context)
10.ServletContextAware's setServletContext (only applicable when running in a web application context)
11.postProcessBeforeInitialization methods of BeanPostProcessors
12.InitializingBean's afterPropertiesSet
13.a custom init-method definition
14.postProcessAfterInitialization methods of BeanPostProcessors

注:其中4,5,6,7,8,9,10是在ApplicationContextAwareProcessor.postProcessBeforeInitialization中完成@PostConstruct是在InitDestroyAnnotationBeanPostProcessor的子类CommonAnnotationBeanPostProcessor.

postProcessBeforeInitialization中完成,@PreDestroy是在InitDestroyAnnotationBeanPostProcessor.postProcessBeforeDestruction中完成,

最后完成lifeCycle生命周期回调方法

标签: spring java

本文转载自: https://blog.csdn.net/qq_31359923/article/details/126609087
版权归原作者 @interface 所有, 如有侵权,请联系我们删除。

“Spring源码深度解析”的评论:

还没有评论