关于java:springboot启动流程

4次阅读

共计 42229 个字符,预计需要花费 106 分钟才能阅读完成。

[toc]

前言

​ 为了记录 spring 的学习日志,以笔记的模式将学习过程记录下来,有问题或有脱漏请指出,谢谢!

现将 spring boot 启动流程进行梳理记录。

1. SpringApplication 筹备

@SpringBootApplication
public class DomeApplication extends SpringBootServletInitializer {public static void main(String[] args) {SpringApplication.run(DomeApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {return builder.sources(this.getClass());
    }
}

应用 @SpringBootApplication 注解,标识启动类,它是一个复合注解,标识应用主动拆卸、通过扫描注解注入 bean。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication{}

在启动类中,运行 main 办法,将调用SpringApplication.run

    public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {return run(new Class<?>[] {primarySource}, args);
    }
    
    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {return new SpringApplication(primarySources).run(args);
    }
    
    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {return new SpringApplication(primarySources).run(args);
    }

通过源码看到,在 SpringApplication.run 中,应用 primarySources 结构 SpringApplication对象,而后调用 run 办法。筹备工作在结构器中实现。

    public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        // 用来获取 Resource 和 classLoader 以及加载资源。this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        // 寄存主加载类。this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        // 推断 web 类型:servlet 或 reactive。this.webApplicationType = WebApplicationType.deduceFromClasspath();
        // 获取 ApplicationContextInitializer 的实现类,进行上下文初始化。setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        // 获取利用事件监听器。setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        // 推导入口类。this.mainApplicationClass = deduceMainApplicationClass();}

2. SpringApplication 运行

run 办法执行后,spring 开始正式运行。

public ConfigurableApplicationContext run(String... args) {
    // 计时器启动
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    // 配置服务器环境有无外设:如显示器、鼠标,如果须要这些数据须要 cpu 模仿。configureHeadlessProperty();
    // 获取 spring 运行监听器,从 spring.factories 文件中加载
    // 如: EventPublishingRunListener(SpringApplication application, String[] args)
    SpringApplicationRunListeners listeners = getRunListeners(args);
    // 1. 监听器公布利用筹备启动 ApplicationStartingEvent 事件
    listeners.starting();
    try {
        // 将传入的参数进行封装。ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        //2. 筹备应用程序环境,并触发事件
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        // 设置 Introspector.getBeaninfo 参数是否疏忽与参数 class 关联的所有 beanInfo
        configureIgnoreBeanInfo(environment);
        // 获取横幅对象
        Banner printedBanner = printBanner(environment);
        //3. 依据 webApplicationType 创立对应的 spring context,并注册正文配置处理器
        context = createApplicationContext();
        // spring 启动谬误回调
        exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                                                         new Class[] { ConfigurableApplicationContext.class}, context);
        //4. 筹备 applicationContext
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
               
        //5. 刷新 context
        refreshContext(context);
        
        //11. 上下文刷新后触发
        afterRefresh(context, applicationArguments);
        
        stopWatch.stop();
        if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        // 公布 started 事件
        listeners.started(context);
        callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
        // 异样解决
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }

    try {
        // 触发 running 事件
        listeners.running(context);
    }
    catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    return context;
}
2.1 触发 SpringApplication 开始启动事件

获取 spring.factories 中 key 为 SpringApplicationRunListener 的对象实例。

    // SpringApplication 类中
    private SpringApplicationRunListeners getRunListeners(String[] args) {Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
        return new SpringApplicationRunListeners(logger,
                getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
    }
# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener

创立 EventPublishingRunListener 对象时将 SpringApplication 中的监听器存入播送器中,进行事件播送

public EventPublishingRunListener(SpringApplication application, String[] args) {
   this.application = application;
   this.args = args;
   this.initialMulticaster = new SimpleApplicationEventMulticaster();
   for (ApplicationListener<?> listener : application.getListeners()) {this.initialMulticaster.addApplicationListener(listener);
   }
}
2.2 筹备环境 prepareEnvironment

将系统配置和零碎环境加载进 ConfigurableEnvironment 中,如果有 spring cloud 我的项目 bootstrap上下文,则会优先加载 spring cloud 配置和近程配置。

  
   /**
    * SpringApplication 类中
    * 筹备应用程序环境以及配置。* 将零碎的相干属性和环境变量配置加载进利用配置对象中,并把 main 办法输出参数 args 解析后也退出到利用配置中。*/
   private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
                                                      ApplicationArguments applicationArguments) {
       //1. 依据容器类型创立环境配置
       // 并将零碎的相干属性(systemProperties)和环境变量配置(systemEnvironment)加载进利用配置的对象中
       ConfigurableEnvironment environment = getOrCreateEnvironment();
       
       //2. 设置配置属性转换器、增加利用默认配置、设置 profile
       configureEnvironment(environment, applicationArguments.getSourceArgs());
       
       //3. 将 MutablePropertySources 转换为 ConfigurationPropertySourcesPropertySource,次要充当适配器
       ConfigurationPropertySources.attach(environment);
       
       //4. 公布 ApplicationEnvironmentPreparedEvent 事件
       // 其中 BootstrapApplicationListener 将疏导 spring cloud 上下文,加载 bootstrap 配置文件
       // ConfigFileApplicationListener 加载配置文件(application.yml)listeners.environmentPrepared(environment);
       
       //5. 将 environment 中 spring.main 结尾的配置绑定到 application 实例上
       bindToSpringApplication(environment);
       
       if (!this.isCustomEnvironment) {
           //6. 将 environment 转化为对应容器类型的 Environment 实例
           // StandardServletEnvironment、StandardReactiveWebEnvironment、StandardEnvironment
           environment = new EnvironmentConverter(getClassLoader())
               .convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
       }
       
       //7. 将 MutablePropertySources 转换为 ConfigurationPropertySourcesPropertySource
       ConfigurationPropertySources.attach(environment);
       return environment;
   }
2.3 创立 createApplicationContext

创立时会依据利用类型 webApplicationType 创立对应的 ApplicationContext,并注册默认的 BeanDefinitionRegistryPostProcessor

   /**
    * SpringApplication 类中
    * 创立对应的 ApplicationContext
    */    
    protected ConfigurableApplicationContext createApplicationContext() {
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {switch (this.webApplicationType) {
                case SERVLET:
                        // AnnotationConfigServletWebServerApplicationContext
                    contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
                    break;
                case REACTIVE:
                        // AnnotationConfigReactiveWebServerApplicationContext
                    contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
                    break;
                default:
                        // AnnotationConfigApplicationContext
                    contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
                }
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
            }
        }
        return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    }

   // -------------------------------------------------------
   /**
    * 这三个 ApplicationContext 的结构器中,都会创立 AnnotatedBeanDefinitionReader 和 ClassPathBeanDefinitionScanner
    */    
    public AnnotationConfigServletWebServerApplicationContext() {
        // 依据注解注册 bean
        this.reader = new AnnotatedBeanDefinitionReader(this);
        // 依据 class path 扫描 bean
        this.scanner = new ClassPathBeanDefinitionScanner(this);
    }
    public AnnotationConfigReactiveWebServerApplicationContext() {this.reader = new AnnotatedBeanDefinitionReader(this);
        this.scanner = new ClassPathBeanDefinitionScanner(this);
    }
    public AnnotationConfigApplicationContext() {this.reader = new AnnotatedBeanDefinitionReader(this);
        this.scanner = new ClassPathBeanDefinitionScanner(this);
    }

   /**
    * AnnotatedBeanDefinitionReader 中会注册几个 BeanDefinitionRegistryPostProcessor
    */    
    public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
        Assert.notNull(environment, "Environment must not be null");
        this.registry = registry;
        this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
        AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
    }

   /**
    * AnnotationConfigUtils.registerAnnotationConfigProcessors 
    * 注册注解后置处理器,将在 refresh 办法中被调用到。*/    
    public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {
        
        // 获取 beanFactory
        DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
        if (beanFactory != null) {
            // 设置默认排序器
            if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
            }
            // 设置主动注入处理器
            if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
            }
        }

        Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

        // 注册 ConfigurationClassPostProcessor, 他反对 @Configuration、@ComponentScans、@ComponentScan、@ImportResource、@Import 等注解进行注册 bean。if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
        }
        
        // 注册 AutowiredAnnotationBeanPostProcessor,反对应用 @Autowired 注解、Setter、@Value 主动注入、xml 配置。if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
        }
        // 反对 jsr250Present 时注册 CommonAnnotationBeanPostProcessor
        // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
        if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
        }
        // 反对 jpa,注册 PersistenceAnnotationBeanPostProcessor
        // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
        if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition();
            try {
                def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
                        AnnotationConfigUtils.class.getClassLoader()));
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException("Cannot load optional framework class:" + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
            }
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
        }
        
        // 注册 EventListenerMethodProcessor,为事件监听器提供反对
        if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
        }
        
        // 注册 DefaultEventListenerFactory,设置默认的监听器工厂
        if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
        }

        return beanDefs;
    }
2.4 筹备 prepareContext

配置 applicationContext,调用 ApplicationContextInitializer 实现类

   /**
    * SpringApplication 中
    * 对 applicationContext 进行初始化设置。*/
   private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
                               SpringApplicationRunListeners listeners, 
                               ApplicationArguments applicationArguments, Banner printedBanner) {
       //1. 设置环境
       context.setEnvironment(environment);
       //2. 设置 beanNameGenerator 和 bean 属性数据类型转换服务
       postProcessApplicationContext(context);
       //3. 调用 ApplicationContextInitializer
       applyInitializers(context);
       //4. 公布 contextPrepared 事件
       listeners.contextPrepared(context);
       if (this.logStartupInfo) {logStartupInfo(context.getParent() == null);
           logStartupProfileInfo(context);
       }
       //5. 获取 beanFactory
       ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
       //6. 注册 args 参数为单例 bean
       beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
       if (printedBanner != null) {
           // 7. 注册 banner 为单例
           beanFactory.registerSingleton("springBootBanner", printedBanner);
       }
       //8. 设置 beanFactory 中能够笼罩定义 bean
       if (beanFactory instanceof DefaultListableBeanFactory) {((DefaultListableBeanFactory) beanFactory)
                   .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
       }
       //9. 启用懒加载所有 bean:在 spring 启动时不会加载 bean,会在应用时进行加载
       if (this.lazyInitialization) {context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
       }
       //10 加载 main 办法所在的主类
       Set<Object> sources = getAllSources();
       Assert.notEmpty(sources, "Sources must not be empty");
       //11 将主类加载进 beanFactory 中
       load(context, sources.toArray(new Object[0]));
       //12 触发 contextLoade 事件
       listeners.contextLoaded(context);
   }

   /**
    * SpringApplication 中
    * 2. 设置 applicationContext
    */    
    protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
        //2.1 注册 bean 名称生成器
        if (this.beanNameGenerator != null) {context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
                    this.beanNameGenerator);
        }
        //2.2 为上下文设置 资源加载器 resourceLoader 和 classLoader
        if (this.resourceLoader != null) {if (context instanceof GenericApplicationContext) {((GenericApplicationContext) context).setResourceLoader(this.resourceLoader);
            }
            if (context instanceof DefaultResourceLoader) {((DefaultResourceLoader) context).setClassLoader(this.resourceLoader.getClassLoader());
            }
        }
        //2.3 注册类型转换服务:ConversionService
        if (this.addConversionService) {context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance());
        }
    }

   /**
    * SpringApplication 中
    * 3. 调用 ApplicationContextInitializer 初始化接口
    */    
    protected void applyInitializers(ConfigurableApplicationContext context) {for (ApplicationContextInitializer initializer : getInitializers()) {
            // 查看泛型的类型与 context 统一
            Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
                    ApplicationContextInitializer.class);
            Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
            initializer.initialize(context);
        }
    }
2.5 加载或刷新 refreshContext

该办法次要是将应用程序中的 bean 注册到 spring application context 中,也就是 BeanFactory 中,进行对立治理;并且在注册前后对 bean 进行加强解决,如BeanDefinitionRegistryPostProcessor \`BeanFactoryPostProcessor`,加强 bean 的注册。

 
   /**
    * SpringApplication 中
    */    
    private void refreshContext(ConfigurableApplicationContext context) {if (this.registerShutdownHook) {
            try {
                // 注册容器敞开钩子
                context.registerShutdownHook();}
            catch (AccessControlException ex) {// Not allowed in some environments.}
        }
        refresh((ApplicationContext) context);
    }

    /**
     * SpringApplication 中
     * 加载或刷新 springContext 
     */
    @Override
    public void refresh() throws BeansException, IllegalStateException {
        // 同步
        synchronized (this.startupShutdownMonitor) {
            //1 筹备上下文刷新:将 applicationContext 标记为 active 状态
            prepareRefresh();

            //2 刷新 beanFactory
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            //3 筹备 beanFactory,并手动注册一些 bean、增加 BeanPostProcessor
            prepareBeanFactory(beanFactory);

            try {
                //4 对 beanFactory 进行后置解决,交由子类实现
                postProcessBeanFactory(beanFactory);

                //5 调用曾经注册的 BeanFactoryPostProcessors:如从 xml 中以及用 scan 扫描 java config、Component、configuration 加载 java bean Definition 到 beanFactory 中
                invokeBeanFactoryPostProcessors(beanFactory);

                //6 注册 BeanPostProcessor,仅仅是注册,调用在 getBean 的时候
                registerBeanPostProcessors(beanFactory);

                //7 初始化国际化资源 i18n
                initMessageSource();

                //8 初始化事件播送器
                initApplicationEventMulticaster();

                //9 留给子类实现的刷新办法,在子类中,会创立对应的 web 容器:tomcat、jetty
                onRefresh();

                //10 注册事件监听器
                registerListeners();

                //11 初始化非懒加载的 bean
                finishBeanFactoryInitialization(beanFactory);

                //12 最初一步,实现刷新过程,公布利用事件
                finishRefresh();}
            catch (BeansException ex) {if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization -" +
                                "cancelling refresh attempt:" + ex);
                }
                // 产生异样,则将曾经初始化的 bean 登记掉
                destroyBeans();

                // Reset 'active' flag.
                // 勾销刷新,将 active 置为 false
                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();}
        }
    }
    


2.5.1 beanFactory 刷新筹备

将 spring context 标记为激活状态(active),并且初始化和验证配置文件,保障配置能被正确解析和指定的配置属性必须存在。

    /**
     * AbstractApplicationContext 中
     * 1. 筹备刷新 
     */    
    protected void prepareRefresh() {
        // Switch to active.
        this.startupDate = System.currentTimeMillis();
        //1.1 激活
        this.closed.set(false);
        this.active.set(true);

        if (logger.isDebugEnabled()) {if (logger.isTraceEnabled()) {logger.trace("Refreshing" + this);
            }
            else {logger.debug("Refreshing" + getDisplayName());
            }
        }

        // Initialize any placeholder property sources in the context environment.
        //1.2 在上下文环境中初始化配置的占位符,启动时为空实现
        initPropertySources();

        // Validate that all properties marked as required are resolvable:
        // see ConfigurablePropertyResolver#setRequiredProperties
        //1.3 对所有的必要属性进行验证,如果有必要的属性没有配置,则会抛出异样
        getEnvironment().validateRequiredProperties();

        //1.4 保留刷新之前的监听器
        // Store pre-refresh ApplicationListeners...
        if (this.earlyApplicationListeners == null) {this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
        }
        else {
            // 将监听器的状态重置
            // Reset local application listeners to pre-refresh state.
            this.applicationListeners.clear();
            this.applicationListeners.addAll(this.earlyApplicationListeners);
        }

        //1.5 收集事件,一旦播送器筹备好就能够公布事件
        // Allow for the collection of early ApplicationEvents,
        // to be published once the multicaster is available...
        this.earlyApplicationEvents = new LinkedHashSet<>();}


2.5.2 beanFactory 获取
    /**
     * AbstractApplicationContext 中
     */        
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        //2.1 能够在该办法中刷新 beanFactory,如替换新的 beanFactory、重新配置 beanFactory 等。refreshBeanFactory();
        //2.2 获取更新后的 beanFactory
        return getBeanFactory();}
2.5.3 beanFactory 配置
    /**
     * AbstractApplicationContext 中
     * 3. 设置 beanFactory 
     */    
    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // Tell the internal bean factory to use the context's class loader etc.
        //3.1 设置类加载器
        beanFactory.setBeanClassLoader(getClassLoader());
        //3.2 设置 el 表达式解析器
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        // 
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

        // Configure the bean factory with context callbacks.
        //3.3 增加 BeanPostProcessor,实现与 bean 相干的 XXXAware 接口的注入工作
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
        //3.4 疏忽这些接口的实现类中的依赖主动注入(setter 注入),接口的依赖由 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);

        //3.5 注册主动拆卸对象,这样 BeanFactory/ApplicationContext 尽管没有以 bean 的形式被定义在工厂中,也反对主动注入。// BeanFactory interface not registered as resolvable type in a plain factory.
        // MessageSource registered (and found for autowiring) as a bean.
        beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
        beanFactory.registerResolvableDependency(ResourceLoader.class, this);
        beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
        beanFactory.registerResolvableDependency(ApplicationContext.class, this);

        //3.6 在 bean 初始化后,查看该 bean 是否为 ApplicationListener,如是则将其退出到 SpringContext 中
        // Register early post-processor for detecting inner beans as ApplicationListeners.
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

        // Detect a LoadTimeWeaver and prepare for weaving, if found.
        //3.7 https://www.cnblogs.com/wade-luffy/p/6078446.html
        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()));
        }

        //3.8 注册默认的环境单例对象
        // Register default environment beans.
        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());
        }
    }
2.5.4 beanFactory 后置解决
    
    /**
     * AbstractApplicationContext 中
     * 对 beanFactory 进行后置解决,交由子类实现
     */    
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {}
2.5.5 beanFactory 后置处理器调用

​ 首先依据程序策略调用 BeanDefinitionRegistryPostProcessor 实现类。

​ 之后依据程序策略调用 BeanFactoryPostProcessor 实现类,同时实现了 BeanDefinitionRegistryPostProcessorBeanFactoryPostProcessor接口的实现类比只实现 BeanFactoryPostProcessor 接口的实现类先调用。

程序策略:优先调用实现了 PriorityOrdered 接口的实现类、在调用实现了 Ordered 接口的实现类,之后调用未实现后面两个接口的实现类。

BeanDefinitionRegistryPostProcessor接口提供了能够注册、删除 BeanDefinition 的反对,BeanFactoryPostProcessor 接口提供了增加或批改 BeanDefinition 的属性反对。 这两个接口执行时,操作的是 BeanDefinition,这时 bean 还未被实例化的

createApplicationContext 办法中会加载 ConfigurationClassPostProcessorAutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor,这几个 beanFactory 后置处理器将会在这里执行,进行扫描须要由 spring 治理的 BeanDefinition

  
   /**
    * AbstractApplicationContext 中
    * 5. 调用 beanFactory 后置处理器
    */    
    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        //5.1 理论调用
        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 
     * 5.1 调用 beanFactory 后置处理器
     * 后置处理器的执行流程
     */    
    public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

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

        // beanFactory 是 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) {
                // 为 BeanDefinitionRegistryPostProcessor 实现类设置 BeanDefinitionRegistry
                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                    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<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

            // 获取 BeanDefinitionRegistryPostProcessor 类型的 bean 名称汇合,// 首先执行实现了 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor 实现类。// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            String[] postProcessorNames =
                    beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                // 将实现了 PriorityOrdered 的 BeanDefinitionRegistryPostProcessor 对象退出汇合
                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            // 对实现了 PriorityOrdered 的 BeanDefinitionRegistryPostProcessor 进行排序
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            // 退出到 registryProcessors 汇合中,对 注册处理器进行汇总
            registryProcessors.addAll(currentRegistryProcessors);
           
            // 调用钩子:BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry
            // bean 定义曾经被加载,然而没有实例化的,容许增加自定义的 bean 定义
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();

            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            // 执行实现了 Ordered 接口的 BeanDefinitionRegistryPostProcessor。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);
            
            // 调用钩子:BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry
            // 实现 PriorityOrdered 接口比实现 Ordered 接口的实现类先执行
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            // 清空以后汇合
            currentRegistryProcessors.clear();

            // 执行其余的 BeanDefinitionRegistryPostProcessors。// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            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();}
            // 执行 BeanFactoryPostProcessor 和 BeanDefinitionRegistryPostProcessor 的独特实现类的 postProcessBeanFactory()。// 所有的 bean 定义曾经被加载,能够增加或批改其中的属性值,在 BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry 前面执行。// 保障 spring 提供的 BeanFactoryPostProcessor 实现类先被执行
            // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
            invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
            invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
        }
        else {
            // Invoke factory processors registered with the context instance.
            invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
        }

        // 执行其余未执行 postProcessBeanFactory() 办法的 BeanFactoryPostProcessor 实现类。// 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, true, false);

        // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
        // Ordered, and the rest.
        List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        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.
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        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));
        }
        sortPostProcessors(orderedPostProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

        // Finally, invoke all other BeanFactoryPostProcessors.
        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();}
2.5.6 beanFactory 注册 BeanPostProcessors

注册 BeanPostProcessor 实现,BeanPostProcessor 反对对 bean 进行加强,在 bean 创立前后进行非凡操作。

/**
 * postProcessBeforeInitialization:在创立好 bean 之后执行,反对在 bean 创立后进行加强,比方批改 bean 的属性、应用代理进行代理。*
 * postProcessAfterInitialization:在执行了 bean 的 init 办法后执行(实现了 `InitializingBean#afterPropertiesSet()` 接口或 xml 配置中指定了 init-method 属性的 bean)。* postProcessAfterInitialization 办法与 postProcessBeforeInitialization 办法一样,只是执行机会不一样,一个是在执行 init 办法之前,一个是在 init 办法之后。*/    
public interface BeanPostProcessor {

    /**
     * InitializingBean#afterPropertiesSet() 之前执行
     */
    @Nullable
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {return bean;}

    /**
     * InitializingBean#afterPropertiesSet() 之后执行
     */
    @Nullable
    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {return bean;}
}

注册 BeanPostProcessors。

    /**
     * 
     * AbstractApplicationContext 中
     */    
    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }

    /**
     * PostProcessorRegistrationDelegate.registerBeanPostProcessors 
     * 5.1 向 BeanFactory 注册 BeanPostProcessors 
     */    
    public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
        
        // 获取 BeanPostProcessor 实现类的 bean 名称
        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.
        // 记录 bean 处理器的总数,用于记录执行过的处理器与记录的处理器个数是否统一
        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

        // Separate between BeanPostProcessors that implement PriorityOrdered,
        // Ordered, and the rest.
        // 将处理器依照实现的接口进行拆分。// 实现了 PriorityOrdered 接口的 BeanPostProcessor
        List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        // 外部 BeanPostProcessor,也就是实现了 MergedBeanDefinitionPostProcessor 接口的类
        List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
        // 实现类 Order 接口的类
        List<String> orderedPostProcessorNames = new ArrayList<>();
        // 未实现 Order 接口的类
        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);
                // 记录外部 BeanPostProcessor
                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 接口的 BeanPostProcessors,包含了外部 BeanPostProcessors
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

        // Next, register the BeanPostProcessors that implement Ordered.
        // 排序并注册实现了 Ordered 接口的 BeanPostProcessors
        List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
        for (String ppName : orderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            orderedPostProcessors.add(pp);
            // 记录外部 BeanPostProcessor
            if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);
            }
        }
        sortPostProcessors(orderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, orderedPostProcessors);

        // 注册未实现 Order 接口的 BeanPostProcessors
        // Now, register all regular BeanPostProcessors.
        List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
        for (String ppName : nonOrderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            nonOrderedPostProcessors.add(pp);
            // 记录外部 BeanPostProcessor
            if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);
            }
        }
        registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

        // 排序并从新注册外部 BeanPostProcessors
        // Finally, re-register all internal BeanPostProcessors.
        sortPostProcessors(internalPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, internalPostProcessors);

        // 将监听器后置处理器注册在最初,以记录监听器。// Re-register post-processor for detecting inner beans as ApplicationListeners,
        // moving it to the end of the processor chain (for picking up proxies etc).
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }
2.5.7 初始化 MessageSource

初始化 MessageSource,将 MessageSource委托给 DelegatingMessageSource,并注册进 beanFactory 中

    
    /**
     * AbstractApplicationContext 中
     */    
    protected void initMessageSource() {ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
            // Make MessageSource aware of parent 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.isTraceEnabled()) {logger.trace("Using MessageSource [" + this.messageSource + "]");
            }
        }
        else {
            // Use empty MessageSource to be able to accept getMessage calls.
            DelegatingMessageSource dms = new DelegatingMessageSource();
            dms.setParentMessageSource(getInternalParentMessageSource());
            this.messageSource = dms;
            beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
            if (logger.isTraceEnabled()) {logger.trace("No'" + MESSAGE_SOURCE_BEAN_NAME + "'bean, using [" + this.messageSource + "]");
            }
        }
    }
2.5.8 初始化事件播送器
    /**
     * 注册事件播送器,默认应用 SimpleApplicationEventMulticaster
     */
    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.isTraceEnabled()) {logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
            }
        }
        else {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() + "]");
            }
        }
    }
2.5.9 初始化其余非凡 bean
    // AbstractApplicationContext
    protected void onRefresh() throws BeansException {// For subclasses: do nothing by default.}
    
    // ServletWebServerApplicationContext
    @Override
    protected void onRefresh() {super.onRefresh();
        try {createWebServer();
        }
        catch (Throwable ex) {throw new ApplicationContextException("Unable to start reactive web server", ex);
        }
    }

    // ServletWebServerApplicationContext,创立 web 服务
    private void createWebServer() {
        WebServerManager serverManager = this.serverManager;
        if (serverManager == null) {String webServerFactoryBeanName = getWebServerFactoryBeanName();
            ReactiveWebServerFactory webServerFactory = getWebServerFactory(webServerFactoryBeanName);
            boolean lazyInit = getBeanFactory().getBeanDefinition(webServerFactoryBeanName).isLazyInit();
            this.serverManager = new WebServerManager(this, webServerFactory, this::getHttpHandler, lazyInit);
            getBeanFactory().registerSingleton("webServerGracefulShutdown",
                    new WebServerGracefulShutdownLifecycle(this.serverManager));
            getBeanFactory().registerSingleton("webServerStartStop",
                    new WebServerStartStopLifecycle(this.serverManager));
        }
        initPropertySources();}
2.5.10 注册事件到事件播送器中

注册事件监听器,并公布晚期事件

    /**
     * AbstractApplicationContext
     */
    protected void registerListeners() {
        // 注册在 spring boot 启动时创立的监听器实例到事件播送器中:// SpringApplication#prepareContext() 和 SpringApplication#applyInitializers() 中执行
        // ApplicationContextInitializer#initialize 时,增加的监听器
        for (ApplicationListener<?> listener : getApplicationListeners()) {getApplicationEventMulticaster().addApplicationListener(listener);
        }

        // 查找利用中 ApplicationListener 实现类,获取 beanName,注册到播送器中
        String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
        for (String listenerBeanName : listenerBeanNames) {getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
        }

        // 播送在之前捕捉到的事件(在容器初始化完 bean 前公布的事件将会暂存在 earlyApplicationEvents 中,进行提早公布)// Publish early application events now that we finally have a multicaster...
        Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
        // 这之后的事件都间接公布,不在暂存到 earlyApplicationEvents 中进行提早公布
        this.earlyApplicationEvents = null;
        if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {for (ApplicationEvent earlyEvent : earlyEventsToProcess) {getApplicationEventMulticaster().multicastEvent(earlyEvent);
            }
        }
    }
2.5.11 实例化残余非 lazy load bean

除懒加载标记的 bean 外,都将在这一步进行实例化。

    /**
     * Finish the initialization of this context's bean factory,
     * initializing all remaining singleton beans.
     */
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Initialize conversion service for this context.
        // 注册类型转换服务:ConversionService,在 SpringApplication#postProcessApplicationContext 中默认曾经注册
        // 这里进行再次查看
        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.
        // 再次查看是否有字符串转换器:StringValueResolver,没有则将解析委托给 PropertySourcesPropertyResolver
        if (!beanFactory.hasEmbeddedValueResolver()) {beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
        }

        // 先创立 LoadTimeWeaverAware 类型的实例 bean
        // 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);
        
        // 容许缓存 bean definition 
        // Allow for caching all bean definition metadata, not expecting further changes.
        beanFactory.freezeConfiguration();

        // 实例化不是懒加载的 bean
        // Instantiate all remaining (non-lazy-init) singletons.
        beanFactory.preInstantiateSingletons();}

    /**
     * 实例化单例对象
     */ 
    @Override
    public void preInstantiateSingletons() throws BeansException {if (logger.isTraceEnabled()) {logger.trace("Pre-instantiating singletons in" + this);
        }

        // Iterate over a copy to allow for init methods which in turn register new bean definitions.
        // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
        
        // 创立非懒加载的实例对象
        // Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
            // 获取顶层 bean 定义
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            // 不是形象、单例、非懒加载
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                // 判断是否是工程 bean
                if (isFactoryBean(beanName)) {
                    // 如果是工程 bean,则增加前缀进行查找
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {FactoryBean<?> factory = (FactoryBean<?>) bean;
                        // 是否立刻创立 bean
                        boolean isEagerInit;
                        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
                                    getAccessControlContext());
                        }
                        else {
                            isEagerInit = (factory instanceof SmartFactoryBean &&
                                    ((SmartFactoryBean<?>) factory).isEagerInit());
                        }
                        // 如果须要立刻创立,则马上创立
                        if (isEagerInit) {getBean(beanName);
                        }
                    }
                }
                else {
                    // 非 beanFactory 的,则马上创立
                    getBean(beanName);
                }
            }
        }
        
        // Trigger post-initialization callback for all applicable beans...
        for (String beanName : beanNames) {
            // 获取单例对象,如果这个对象是 SmartInitializingSingleton 接口的实现类,// 则调用 afterSingletonsInstantiated() 办法
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }, getAccessControlContext());
                }
                else {smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }
2.5.12 最初一步刷新实现
    /**
     * AbstractApplicationContext
     */
    protected void finishRefresh() {
        // 革除上下文中的资源缓存
        // Clear context-level resource caches (such as ASM metadata from scanning).
        clearResourceCaches();

        // 注册 LifecycleProcessor 接口实现类,默认应用 DefaultLifecycleProcessor
        // Initialize lifecycle processor for this context.
        initLifecycleProcessor();

        // 触发刚刚注册的 LifecycleProcessor 接口实现类的 onRefresh 事件
        // Propagate refresh to lifecycle processor first.
        getLifecycleProcessor().onRefresh();

        // 公布上下文刷新实现事件
        // Publish the final event.
        publishEvent(new ContextRefreshedEvent(this));

        // 想 bean 视图注册上下文对象。// Participate in LiveBeansView MBean, if active.
        LiveBeansView.registerApplicationContext(this);
    }

总结

spring boot 启动流程次要通过初始化和加载监听器、筹备应用程序环境(配置信息)、创立容器上下文、刷新容器上下文,其中最要害的是刷新上下文 refresh。在刷新上下文中,加载 BeanFactoryPostProcessor,应用 BeanFactoryPostProcessor加载程序中须要注入的BeanDefinition,筹备事件播送器,最初创立单例并且不是懒加载的 bean。

spring 提供的后置处理器执行程序:

  1. BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(BeanDefinitionRegistry)

    动静注册、批改与删除 BeanDefinition

  2. BeanFactoryPostProcessor#postProcessBeanFactory(ConfigurableListableBeanFactory)

    增加或批改 BeanDefinition 的属性

  3. doCreateBean

    创立 bean

  4. 对 bean 注入依赖
  5. BeanPostProcessor#postProcessBeforeInitialization()

    创立 bean 之后,在对 bean 进行注入依赖对象后,调用这个 bean 后置处理器。

  6. InitializingBean#afterPropertiesSet

    spring 提供的 bean 进行初始化接口

  7. BeanPostProcessor#postProcessAfterInitialization()

    bean 初始化实现后执行。

    如果是 InitializingBean的实现类,则在 afterPropertiesSet 办法执行后执行,否则在BeanPostProcessor#postProcessBeforeInitialization() 之后执行。

正文完
 0