小工具知识网

当前位置: 首页 > 行业知识 > SpringBoot——启动类的原理

行业知识

SpringBoot——启动类的原理

2026-11-17 20:15:17 来源:互联网转载

优质博���:IT-BLOG-CN

SpringBoot启动类上使用@SpringBootApplication注解,该注解是一个组合注解,包含多个其它注解。和类定义SpringApplication.run要揭开SpringBoot的神秘面纱,我们要从这两位开始就可以了。

@SpringBootApplicationpublic class MySpringbootApplication {    public static void main(String[] args) {        SpringApplication.run(MySpringbootApplication.class, args);    }}

一、@SpringBootApplication

@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 {

@SpringBootApplication注解上标有三个注解@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan。其它四个注解用来声明SpringBootAppliction为一个注解。

@SpringBootConfiguration

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Configurationpublic @interface SpringBootConfiguration {

@SpringBootConfiguration注解中没有定义任何属性信息,而该注解上有一个注解@Configuration,用于标识配置类。所以@SpringBootConfiguration注解的功能和@Configuration注解的功能相同,用于标识配置类,与@Bean搭配使用,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。如下案例:

@Configuration public class Conf {       @Bean       public Car car() {           return new Car();       }}

@ComponentScan

@ComponentScan这个注解在Spring中很重要,它对应XML配置中的元素,@ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义,最终将这些bean定义加载到IoC容器中。我们可以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。注:所以SpringBoot的启动类最好是放在root package下,因为默认不指定basePackages。

@EnableAutoConfiguration

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@AutoConfigurationPackage@Import({AutoConfigurationImportSelector.class})public @interface EnableAutoConfiguration {

个人感觉@EnableAutoConfiguration这个Annotation最为重要,Spring框架提供的各种名字为@Enable开头的Annotation,借助@Import的支持,收集和注册特定场景相关的bean定义。@EnableAutoConfiguration也是借助@Import的帮助,将所有符合自动配置条件的bean定义加载到IoC容器。@EnableAutoConfiguration注解上标注了两个注解,@AutoConfigurationPackage、@Import。@Import注解在SpringIOC一些注解的源码中比较常见,主要用来给容器导入目标bean。这里@Import注解给容器导入的组件用于自动配置:AutoConfigurationImportSelector而@AutoConfigurationPackage注解是Spring自定义的注解,用于将主配置类所在的包作为自动配置的包进行管理。

@AutoConfigurationPackage

package org.springframework.boot.autoconfigure;@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@Import({Registrar.class})public @interface AutoConfigurationPackage {    String[] basePackages() default {};    Class[] basePackageClasses() default {};}

@AutoConfigurationPackage注解上的@Import注解,给容器导入了Registrar组件

Registrar

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {    Registrar() {    }    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {        AutoConfigurationPackages.register(registry, (String[])(new AutoConfigurationPackages.PackageImports(metadata)).getPackageNames().toArray(new String[0]));    }    public Set determineImports(AnnotationMetadata metadata) {        return Collections.singleton(new AutoConfigurationPackages.PackageImports(metadata));    }}

Registrar是抽象类AutoConfigurationPackages的内部静态类,Registrar内的registerBeanDefinitions()方法负责将注解所在的包及其子包下的所有组件注册进容器。这也是为什么SpringBoot的启动类要在其他类的父包或在同一个包中。

AutoConfigurationImportSelector

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

借助AutoConfigurationImportSelector,@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建的IoC容器中。借助于 Spring框架原有的一个工具类:SpringFactoriesLoader,@EnableAutoConfiguration的自动配置功能才得以大功告成!

SpringFactoriesLoader属于Spring框架私有的一种扩展方案,其主要功能就是从指定的配置文件META-INF/spring.factories 加载配置。

public abstract class SpringFactoriesLoader {    public static  List loadFactories(Class factoryClass, ClassLoader classLoader) {        ......    }    public static List loadFactoryNames(Class factoryClass, ClassLoader classLoader) {        ......    }}

配合@EnableAutoConfiguration使用的话,它更多是提供一种配置查找的功能支持,即根据@EnableAutoConfiguration的完整类名org.springframework.boot.autoconfigure.EnableAutoConfiguration作为查找的Key,获取对应的一组@Configuration类。

上图就是从SpringBoot的autoconfigure依赖包中的META-INF/spring.factories配置文件中摘录的一段内容,可以很好地说明问题。

所以,@EnableAutoConfiguration自动配置的魔法骑士就变成了:从classpath中搜寻所有的META-INF/spring.factories配置文件,并将其中org.springframework.boot.autoconfigure.EnableutoConfiguration对应的配置项通过反射Java Refletion实例化,为标注了@Configuration的配置类加载到IoC容器中。

AutoConfigurationImportSelector类实现了很多Aware接口,而Aware接口的功能是使用一些Spring内置的实例获取一些想要的信息,如容器信息、环境信息、容器中注册的bean信息等。而 AutoConfigurationImportSelector类的作用是将Spring中已经定义好的自动配置类注入容器中,而实现该功能的方法是selectImports方法:

selectImports

注册Spring中定义好的配置类

public String[] selectImports(AnnotationMetadata annotationMetadata) {    if (!this.isEnabled(annotationMetadata)) {        return NO_IMPORTS;    } else {        AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);        AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());    }}

@EnableAutoConfiguration:SpringBoot根据应用所声明的依赖来对Spring框架进行自动配置。

@SpringBootConfiguration(内部为@Configuration):被标注的类等于在Spring的XML配置文件中(applicationContext.xml),装配所有Bean事务,提供了一个Spring的上下文环境。

@ComponentScan:组件扫描,可自动发现和装配Bean,默认扫描SpringApplication的run方法里的Booter.class所在的包路径下文件,所以最好将该启动类放到根包路径下。

二、SpringApplication.run(x.class, args)

SpringApplication的run方法的实现是SpringApplication执行流程的主要线路,该方法的主要流程大体可以归纳如下:

【1】如果我们使用的是SpringApplication的静态run方法,那么,这个方法里面首先要创建一个SpringApplication对象实例,然后调用这个创建好的SpringApplication的实例方法。在 SpringApplication实例初始化的时候,它会提前做几件事情:

 ● 根据classpath里面是否存在某个特征类org.springframework.web.context.ConfigurableWebApplicationContext来决定是否应该创建一个为Web应用使用的ApplicationContext类型。

 ● 使用SpringFactoriesLoader在应用的classpath中查找并加载所有可用的ApplicationContextInitializer。

 ● 使用SpringFactoriesLoader在应用的classpath中查找并加载所有可用的ApplicationListener。

 ● 推断并设置main方法的定义类。

【2】SpringApplication完成实例初始化并且完成设置后,就开始执行run方法的逻辑,首先遍历执行所有通过SpringFactoriesLoader可以查找到并加载的 SpringApplicationRunListener[接口]。调用它们的started()方法,告诉这些SpringApplicationRunListener,“嘿,SpringBoot应用要开始执行咯!”。

public interface SpringApplicationRunListener {    default void starting() {    }    default void environmentPrepared(ConfigurableEnvironment environment) {    }    default void contextPrepared(ConfigurableApplicationContext context) {    }    default void contextLoaded(ConfigurableApplicationContext context) {    }    default void started(ConfigurableApplicationContext context) {    }    default void running(ConfigurableApplicationContext context) {    }    default void failed(ConfigurableApplicationContext context, Throwable exception) {    }}

【3】创建并配置当前Spring Boot应用将要使用的Environment(包括配置要使用的PropertySource以及Profile)。

【4】遍历调用所有SpringApplicationRunListener的environmentPrepared()的方法,告诉他们:“当前SpringBoot应用使用的Environment准备好了咯!”。

【5】如果SpringApplication的showBanner属性被设置为true,则打印banner。

【6】根据用户是否明确设置了applicationContextClass类型以及初始化阶段的推断结果,决定该为当前SpringBoot应用创建什么类型的ApplicationContext并创建完成,然后根据条件决定是否添加 ShutdownHook,决定是否使用自定义的BeanNameGenerator,决定是否使用自定义的ResourceLoader,当然,最重要的,将之前准备好的Environment设置给创建好的ApplicationContext使用。

【7】ApplicationContext创建好之后,SpringApplication会再次借助SpringFactoriesLoader,查找并加载classpath中所有可用的ApplicationContextInitializer,然后遍历调用这些 ApplicationContextInitializer的 initialize(applicationContext)方法来对已经创建好的ApplicationContext进行进一步的处理。

【8】遍历调用所有SpringApplicationRunListener的contextPrepared()方法。

【9】最核心的一步,将之前通过 @EnableAutoConfiguration获取的所有配置以及其他形式的 IoC容器配置加载到已经准备完毕的ApplicationContext。

【10】遍历调用所有SpringApplicationRunListener的contextLoaded()方法。

【11】调用ApplicationContext的refresh()方法,完成IoC容器可用的最后一道工序。

【12】查找当前ApplicationContext中是否注册有CommandLineRunner,如果有,则遍历执行它们。

【13】正常情况下,遍历执行SpringApplicationRunListener的finished()方法、(如果整个过程出现异常,则依然调用所有SpringApplicationRunListener的finished()方法,只不过这种情况下会将异常信息一并传入处理)

去除事件通知点后,整个流程如下:

调试一个SpringBoot启动程序为例,参考流程中主要类类图,来分析其启动逻辑和自动化配置原理。

上图为SpringBoot启动结构图,我们发现启动流程主要分为三个部分:

第一部分进行 SpringApplication的初始化模块,配置一些基本的环境变量、资源、构造器、监听器

第二部分实现了应用具体的启动方案,包括启动流程的监听模块、加载配置环境模块、及核心的创建上下文环境模块

第三部分是自动化配置模块,该模块作为SpringBoot自动配置核心,在后面的分析中会详细讨论。在下面的启动程序中我们会串联起结构中的主要功能

SpringBoot启动类

进入run()方法,run()方法创建了一个SpringApplication实例并调用其run()方法。

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

SpringApplication构造器主要为SpringApplication对象赋一些初值。构造函数执行完毕后,回到run()方法

public ConfigurableApplicationContext run(String... args) {    StopWatch stopWatch = new StopWatch();    stopWatch.start();    ConfigurableApplicationContext context = null;    Collection exceptionReporters = new ArrayList();    this.configureHeadlessProperty();    SpringApplicationRunListeners listeners = this.getRunListeners(args);    listeners.starting();    Collection exceptionReporters;    try {        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);        this.configureIgnoreBeanInfo(environment);        Banner printedBanner = this.printBanner(environment);        context = this.createApplicationContext();        exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);        this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);        this.refreshContext(context);        this.afterRefresh(context, applicationArguments);        stopWatch.stop();        if (this.logStartupInfo) {            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);        }        listeners.started(context);        this.callRunners(context, applicationArguments);    } catch (Throwable var10) {        this.handleRunFailure(context, var10, exceptionReporters, listeners);        throw new IllegalStateException(var10);    }    try {        listeners.running(context);        return context;    } catch (Throwable var9) {        this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);        throw new IllegalStateException(var9);    }}

该方法中实现了如下几个关键步骤:

【1】创建了应用的监听器SpringApplicationRunListeners并开始监听;

【2】加载SpringBoot配置环境ConfigurableEnvironment,如果是通过web容器发布,会加载StandardEnvironment,其最终也是继承了ConfigurableEnvironment,类图如下:

可以看出,*Environment最终都实现了PropertyResolver接口,我们平时通过environment对象获取配置文件中指定Key对应的value方法时,就是调用了propertyResolver接口的getProperty方法;

【3】配置环境Environment加入到监听器对象中SpringApplicationRunListeners;

【4】创建run方法的返回对象:ConfigurableApplicationContext(应用配置上下文),我们可以看一下创建方法:

protected ConfigurableApplicationContext createApplicationContext() {    Class contextClass = this.applicationContextClass;    if (contextClass == null) {        try {            switch(this.webApplicationType) {            case SERVLET:                contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");                break;            case REACTIVE:                contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");                break;            default:                contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");            }        } catch (ClassNotFoundException var3) {            throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);        }    }    return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);}

会先获取显式设置的应用上下文applicationContextClass,如果不存在,再加载默认的环境配置(通过是否是web environment判断),默认选择AnnotationConfigApplicationContext注解上下文(通过扫描所有注解类来加载bean),最后通过BeanUtils实例化上下文对象,并返回。

ConfigurableApplicationContext类图如下:

主要看其继承的两个方向:

LifeCycle: 生命周期类,定义了start启动、stop结束、isRunning是否运行中等生命周期空值方法;

ApplicationContext: 应用上下文类,其主要继承了beanFactory(bean的工厂类);

【5】回到run方法内,prepareContext方法将listeners、environment、applicationArguments、banner等重要组件与上下文对象关联;

【6】接下来的refreshContext(context)方法(初始化方法如下)将是实现 spring-boot-starter-*(mybatis、redis等)自动化配置的关键,包括spring.factories的加载,bean的实例化等核心工作。SpringIOC源码refresh方法链接 有兴趣的可以看下。

private void refreshContext(ConfigurableApplicationContext context) {    this.refresh((ApplicationContext)context);}//进入 refresh 方法,IOC容器着重分析的方法public void refresh() throws BeansException, IllegalStateException {    synchronized(this.startupShutdownMonitor) {        this.prepareRefresh();        ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();        this.prepareBeanFactory(beanFactory);        try {            this.postProcessBeanFactory(beanFactory);            this.invokeBeanFactoryPostProcessors(beanFactory);            this.registerBeanPostProcessors(beanFactory);            this.initMessageSource();            this.initApplicationEventMulticaster();            this.onRefresh();            this.registerListeners();            this.finishBeanFactoryInitialization(beanFactory);            this.finishRefresh();        } catch (BeansException var9) {            if (this.logger.isWarnEnabled()) {                this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);            }            this.destroyBeans();            this.cancelRefresh(var9);            throw var9;        } finally {            this.resetCommonCaches();        }    }}

配置结束后,SpringBoot做了一些基本的收尾工作,返回了应用环境上下文。回顾整体流程,SpringBoot的启动,主要创建了配置环境environment、事件监听listeners、应用上下文applicationContext,并基于以上条件,在容器中开始实例化我们需要的Bean,至此,通过SpringBoot启动的程序已经构造完成,接下来我们来探讨自动化配置是如何实现。

自动化配置

之前的启动结构图中,我们注意到无论是应用初始化还是具体的执行过程,都调用了SpringBoot自动配置模块。

SpringBoot自动配置模块: 该配置模块的主要使用到了SpringFactoriesLoader,即Spring工厂加载器,该对象提供了loadFactoryNames方法,入参为factoryClass和classLoader,即需要传入上图中的工厂类名称和对应的类加载器,方法会根据指定的classLoader,加载该类加器搜索路径下的指定文件,即spring.factories文件,传入的工厂类为接口,而文件中对应的类则是接口的实现类,或最终作为实现类,所以文件中一般为如下图这种一对多的类名集合,获取到这些实现类的类名后,loadFactoryNames方法返回类名集合,方法调用方得到这些集合后,再通过反射获取这些类的类对象、构造方法,最终生成实例。

# PropertySource Loadersorg.springframework.boot.env.PropertySourceLoader=\org.springframework.boot.env.PropertiesPropertySourceLoader,\org.springframework.boot.env.YamlPropertySourceLoader# Run Listenersorg.springframework.boot.SpringApplicationRunListener=\org.springframework.boot.context.event.EventPublishingRunListener# Error Reportersorg.springframework.boot.SpringBootExceptionReporter=\org.springframework.boot.diagnostics.FailureAnalyzers# Application Context Initializersorg.springframework.context.ApplicationContextInitializer=\org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\

下图有助于我们形象理解自动配置流程。

mybatis-spring-boot-starter starter详细内容链接、spring-boot-starter-web等组件的META-INF文件下均含有spring.factories文件,自动配置模块中,SpringFactoriesLoader收集到文件中的类全名并返回一个类全名的数组,返回的类全名通过反射被实例化,就形成了具体的工厂实例,工厂实例来生成组件具体需要的bean。之前我们提到了EnableAutoConfiguration注解,其类图如下:

可以发现其最终实现了ImportSelector(选择器)和 BeanClassLoaderAware(bean类加载器中间件),重点关注一下 AutoConfigurationImportSelector的selectImports方法。

public String[] selectImports(AnnotationMetadata annotationMetadata) {    if (!this.isEnabled(annotationMetadata)) {        return NO_IMPORTS;    } else {        AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());    }}protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {    if (!this.isEnabled(annotationMetadata)) {        return EMPTY_ENTRY;    } else {        AnnotationAttributes attributes = this.getAttributes(annotationMetadata);        List configurations = this.getCandidateConfigurations(annotationMetadata, attributes);        configurations = this.removeDuplicates(configurations);        Set exclusions = this.getExclusions(annotationMetadata, attributes);        this.checkExcludedClasses(configurations, exclusions);        configurations.removeAll(exclusions);        configurations = this.getConfigurationClassFilter().filter(configurations);        this.fireAutoConfigurationImportEvents(configurations, exclusions);        return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);    }}

该方法在SpringBoot启动流程Bean实例化前被执行,返回要实例化的类信息列表。如果获取到类信息,Spring自然可以通过类加载器将类加载到jvm中,现在我们已经通过SpringBoot的starter依赖方式依赖了我们需要的组件,那么这些组建的类信息在select方法中也是可以被获取到的。

protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {    List configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());    Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");    return configurations;}

该方法中的getCandidateConfigurations方法,其返回一个自动配置类的类名列表,方法调用了loadFactoryNames方法,查看该方法:

public static List loadFactoryNames(Class factoryType, @Nullable ClassLoader classLoader) {    String factoryTypeName = factoryType.getName();    return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());}

在上面的代码可以看到自动配置器会根据传入的factoryType.getName()到项目系统路径下所有的spring.factories文件中找到相应的key,从而加载里面的类。我们就选取这个 mybatis-spring-boot-autoconfigure下的spring.factories文件

# Auto Configureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

进入org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration中,主要看一下类头:

@Configuration@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})@ConditionalOnBean({DataSource.class})@EnableConfigurationProperties({MybatisProperties.class})@AutoConfigureAfter({DataSourceAutoConfiguration.class})public class MybatisAutoConfiguration {

@Configuration,俨然是一个通过注解标注的SpringBean;

@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class})这个注解的意思是:当存在SqlSessionFactory.class, SqlSessionFactoryBean.class这两个类时才解析 MybatisAutoConfiguration配置类,否则不解析这一个配置类,make sence,我们需要mybatis为我们返回会话对象,就必须有会话工厂相关类;

@CondtionalOnBean(DataSource.class):只有处理已经被声明为bean的dataSource;

@ConditionalOnMissingBean(MapperFactoryBean.class)这个注解的意思是如果容器中不存在name指定的bean则创建bean注入,否则不执行(该类源码较长,篇幅限制不全粘贴);

    com.alibaba.cloud    spring-cloud-alibaba-sentinel-gateway    2.1.0.RELEASE

这里是截取的mybatis-spring-boot-starter的源码中pom.xml文件中所有依赖:

          org.springframework.boot      spring-boot-starter              org.springframework.boot      spring-boot-starter-jdbc              org.mybatis.spring.boot      mybatis-spring-boot-autoconfigure              org.mybatis      mybatis              org.mybatis      mybatis-spring    

因为maven依赖的传递性,我们只要依赖starter就可以依赖到所有需要自动配置的类,实现开箱即用的功能。也体现出SpringBoot简化了Spring框架带来的大量XML配置以及复杂的依赖管理,让开发人员可以更加关注业务逻辑的开发。

三、总结

配置文件定义属性[@Configuration],自动装配到所属的配置类中,然后通过动态代理进入spring容器中。

上一篇:轻松下载Cloze秘籍,一站式解决方案助你轻松搞定!

下一篇:电脑主机启动后有气味吗怎么回事