SpringBoot启动全流程源码解析

简介: SpringBoot启动全流程源码解析

SpringBoot启动过程流程图

源码解析

首先,我们先来看下SpringBoot项目的启动类

@SpringBootApplication

  public class SpringDemoApplication {

    public static void main(String[] args) {

    SpringApplication.run(SpringDemoApplication.class, args);

    }

  }

一个是@SpringBootApplication,参考另一篇文章SpringBoot自动配置实现原理及源码解析(2.3.x)

另一个关键点是SpringApplication.run()方法,这是一个静态方法,我们详细看下代码:

/**

  • 静态方法
    */
    public static ConfigurableApplicationContext run(Class<?> primarySource, String… args) {
    return run(new Class<?>[]{primarySource}, args);
    }

/**

  • 调用此方法启动会使用默认设置和用户提供的参数args
    */
    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
    // 实例化SpringApplication,然后调用run
    return new SpringApplication(primarySources).run(args);
    }
    可以看到代码new SpringApplication(),new了一个这个对象,然后调用run,我们先看看SpringApplication构造函数:

public SpringApplication(Class<?>… primarySources) {

this(null, primarySources);

}

public SpringApplication(ResourceLoader resourceLoader, Class<?>… primarySources) {

this.resourceLoader = resourceLoader;

Assert.notNull(primarySources, “PrimarySources must not be null”);

// 把SpringDemoApplication作为primarySources属性存储起来

this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));

// 从classpath中推断是否为web应用

this.webApplicationType = WebApplicationType.deduceFromClasspath();

// 获取启动加载器

this.bootstrappers = new ArrayList<>(getSpringFactoriesInstances(Bootstrapper.class));

// 设置初始化器(Initializer),最后会调用这些功能

setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

// 设置监听器(Listener)

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

// 获取main方法所在的类

this.mainApplicationClass = deduceMainApplicationClass();

}

基本就是做如下几件事情:

配置primarySources

配置环境是否为web环境

创建初始化构造器setInitializers

创建应用监听器

配置应用主方法所在类(就是main方法所在类)

基本上就是做一些必要的属性初始化和赋值,接下来我们看下关键方法run

/**

  • 运行spring应用程序,创建并刷新一个新的 {@link ApplicationContext}.

  • @param args the application arguments (usually passed from a Java main method)
  • @return a running {@link ApplicationContext}
    */
    public ConfigurableApplicationContext run(String… args) {
    // 计时工具
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    // 创建启动上下文对象
    DefaultBootstrapContext bootstrapContext = createBootstrapContext();
    ConfigurableApplicationContext context = null;
    configureHeadlessProperty();
    // 第一步:获取并启动监听器
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting(bootstrapContext, this.mainApplicationClass);
    try {
    ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
    // 第二步:准备环境
    ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
    configureIgnoreBeanInfo(environment);
    // 第三步:打印banner,就是启动的时候在console的spring图案
    Banner printedBanner = printBanner(environment);
    // 第四步:创建spring容器
    context = createApplicationContext();
    context.setApplicationStartup(this.applicationStartup);
    // 第五步:spring容器前置处理
    prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
    // 第六步:刷新容器
    refreshContext(context);
    // 第七步:spring容器后置处理
    afterRefresh(context, applicationArguments);
    stopWatch.stop(); // 结束计时器并打印,这就是我们启动后console的显示的时间
    if (this.logStartupInfo) {
    new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
    }
    // 发出启动结束事件
    listeners.started(context);
    // 执行runner的run方法
    callRunners(context, applicationArguments);
    } catch (Throwable ex) {
    // 异常处理,如果run过程发生异常
    handleRunFailure(context, ex, listeners);
    throw new IllegalStateException(ex);
    }

try {

listeners.running(context);

} catch (Throwable ex) {

// 异常处理,如果run过程发生异常

handleRunFailure(context, ex, null);

throw new IllegalStateException(ex);

}

// 返回最终构建的容器对象

return context;

}

基本流程如下:

启动一个计时器,启动完成后会打印耗时

获取并启动监听器 SpringApplicationRunListeners

配置环境 ConfigurableEnvironment

Banner配置,就是控制台的那个spirng

应用上下文模块(前置处理、刷新、后置处理) ConfigurableApplicationContext

发出启动结束事件并结束计时

这里的每一个方法都是做了很多事情,接下来我们一步步深入看下

run方法第一步:获取并启动监听器

这里的启动监听就是我们需要监听SpringBoot的启动流程监听,实现SpringApplicationRunListener类即可监听

/**

  • 获取运行监听的监听者们,在对应的阶段会发送对应的事件到监听者
  • @param args
  • @return
    */
    private SpringApplicationRunListeners getRunListeners(String[] args) {
    Class<?>[] types = new Class<?>[]{SpringApplication.class, String[].class};
    return new SpringApplicationRunListeners(logger,
    getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args),
    this.applicationStartup);
    }
    1

SpringApplicationRunListener类如下:

public interface SpringApplicationRunListener {

/**

  • 当调用run方法后会立即调用,可以用于非常早期的初始化
    */
    default void starting(ConfigurableBootstrapContext bootstrapContext) {
    starting();
    }

/**

  • 环境准备好之后调用
    */
    default void environmentPrepared(ConfigurableBootstrapContext bootstrapContext,
    ConfigurableEnvironment environment) {
    environmentPrepared(environment);
    }

/**

  • 在加载资源之前,ApplicationContex准备好之后调用
    */
    default void contextPrepared(ConfigurableApplicationContext context) {
    }

/**

  • 在加载应用程序上下文但在其刷新之前调用
    */
    default void contextLoaded(ConfigurableApplicationContext context) {
    }

/**

  • 上下文已经刷新且应用程序已启动且所有{@link CommandLineRunner commandLineRunner}
  • 和{@link ApplicationRunner ApplicationRunners}未调用之前调用
    */
    default void started(ConfigurableApplicationContext context) {
    }

/**

  • 当应用程序上下文被刷新并且所有{@link CommandLineRunner commandLineRunner}
  • 和{@link ApplicationRunner ApplicationRunners}都已被调用时,在run方法结束之前立即调用。
    */
    default void running(ConfigurableApplicationContext context) {
    }

/**

  • 在启动过程发生失败时调用
    */
    default void failed(ConfigurableApplicationContext context, Throwable exception) {
    }
    }

run方法第二步:准备环境

/**

  • 创建并配置SpringBooty应用j将要使用的Environment

  • @param listeners
  • @param bootstrapContext
  • @param applicationArguments
  • @return
    */
    private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
    DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
    // 根据不同的web类型创建不同实现的Environment对象
    ConfigurableEnvironment environment = getOrCreateEnvironment();
    // 配置环境
    configureEnvironment(environment, applicationArguments.getSourceArgs());
    ConfigurationPropertySources.attach(environment);
    // 发送环境已准备完成事件
    listeners.environmentPrepared(bootstrapContext, environment);
    DefaultPropertiesPropertySource.moveToEnd(environment);
    // 根据命令行参数中spring.profiles.active属性配置Environment对象中的activeProfile(比如dev、prod、test)
    configureAdditionalProfiles(environment);
    // 绑定环境中spring.main属性绑定到SpringApplication对象中
    bindToSpringApplication(environment);
    // 如果用户使用spring.main.web-application-type属性手动设置了webApplicationType
    if (!this.isCustomEnvironment) {
    // 将环境对象转换成用户设置的webApplicationType相关类型,他们是继承同一个父类,直接强转
    environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
    deduceEnvironmentClass());
    }
    ConfigurationPropertySources.attach(environment);
    return environment;
    }

这里主要有如下过程:

创建配置环境 ConfigurableEnvironment

加载属性文件资源

配置监听

run方法第三步:打印banner

/**

  • 打印banner

  • @param environment
  • @return
    */
    private Banner printBanner(ConfigurableEnvironment environment) {
    // banner模式,可以是console、log、off
    if (this.bannerMode == Banner.Mode.OFF) {
    return null;
    }
    ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
    : new DefaultResourceLoader(null);
    SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
    if (this.bannerMode == Mode.LOG) {
    return bannerPrinter.print(environment, this.mainApplicationClass, logger);
    }
    return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
    }

基本就是依据不同情况打印banner而已,比较简单

run方法第四步:创建spring容器

最终获取到ConfigurableApplicationContext上下文对象

run方法第五步:spring容器前置处理

/**

  • Spring容器准备
    */
    private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context,
    ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
    ApplicationArguments applicationArguments, Banner printedBanner) {
    // 设置上下文环境
    context.setEnvironment(environment);
    //
    postProcessApplicationContext(context);
    // 执行所有ApplicationContextInitializer对象的initialize方法(这些对象是通过读取spring.factories加载)
    applyInitializers(context);
    // 发布上下文准备完成事件到所有监听器
    listeners.contextPrepared(context);
    bootstrapContext.close(context);
    if (this.logStartupInfo) {
    logStartupInfo(context.getParent() == null);
    logStartupProfileInfo(context);
    }
    //
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    beanFactory.registerSingleton(“springApplicationArguments”, applicationArguments);
    if (printedBanner != null) {
    beanFactory.registerSingleton(“springBootBanner”, printedBanner);
    }
    if (beanFactory instanceof DefaultListableBeanFactory) {
    ((DefaultListableBeanFactory) beanFactory)
    .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
    }
    if (this.lazyInitialization) {
    context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
    }
    // Load the sources
    Set sources = getAllSources();
    Assert.notEmpty(sources, “Sources must not be empty”);
    // 加载bean到上下文
    load(context, sources.toArray(new Object[0]));
    // 发送上下文加载完成事件
    listeners.contextLoaded(context);
    }

run方法第六步:刷新容器【关键】

/**

  • 刷新应用程序上下文

  • @param context
    */
    private void refreshContext(ConfigurableApplicationContext context) {
    // 注册一个关闭钩子,在jvm停止时会触发,然后退出时执行一定的退出逻辑
    if (this.registerShutdownHook) {
    try {
    // 添加:Runtime.getRuntime().addShutdownHook()
    // 移除:Runtime.getRuntime().removeShutdownHook(this.shutdownHook)
    context.registerShutdownHook();
    } catch (AccessControlException ex) {
    // Not allowed in some environments.
    }
    }
    // ApplicationContext真正开始初始化容器和创建bean的阶段
    refresh((ApplicationContext) context);
    }

protected void refresh(ApplicationContext applicationContext) {

Assert.isInstanceOf(ConfigurableApplicationContext.class, applicationContext);

refresh((ConfigurableApplicationContext) applicationContext);

}

protected void refresh(ConfigurableApplicationContext applicationContext) {

applicationContext.refresh();

}

调用应用上下文对象的refresh()方法,接下来我i门到ConfigurableApplicationContext类中去看下这个方法

public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {

void refresh() throws BeansException, IllegalStateException;

}

这是一个接口,且这个类是在spring框架中,非springboot,它的实现类共有三个

AbstractApplicationContext是一个抽象类,其余两个类都继承了它,我们来看看这个抽象类的代码:

@Override

public void refresh() throws BeansException, IllegalStateException {

synchronized (this.startupShutdownMonitor) {

StartupStep contextRefresh = this.applicationStartup.start(“spring.context.refresh”);

// 第一步:准备更新上下时的预备工作

prepareRefresh();

// 第二步:获取上下文内部BeanFactory

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// 第三步:对BeanFactory做预备工作

prepareBeanFactory(beanFactory);

try {

// 第四步:允许在上下文子类中对bean工厂进行post-processing

postProcessBeanFactory(beanFactory);

StartupStep beanPostProcess = this.applicationStartup.start(“spring.context.beans.post-process”);

// 第五步:调用上下文中注册为bean的工厂 BeanFactoryPostProcessor

invokeBeanFactoryPostProcessors(beanFactory);

// 第六步:注册拦截bean创建的拦截器

registerBeanPostProcessors(beanFactory);

beanPostProcess.end();

// 第七步:初始化MessageSource(国际化相关)

initMessageSource();

// 第八步:初始化容器事件广播器(用来发布事件)

initApplicationEventMulticaster();

// 第九步:初始化一些特殊的bean

onRefresh();

// 第十步:将所有监听器注册到前两步创建的事件广播器中

registerListeners();

// 第十一步:结束bean的初始化工作(主要将所有单例BeanDefinition实例化)

finishBeanFactoryInitialization(beanFactory);

// 第十二步:afterRefresh(上下文刷新完毕,发布相应事件)

finishRefresh();

} catch (BeansException ex) {

if (logger.isWarnEnabled()) {

logger.warn("Exception encountered during context initialization - " +

"cancelling refresh attempt: " + ex);

}

// Destroy already created singletons to avoid dangling resources.

destroyBeans();

// Reset ‘active’ flag.

cancelRefresh(ex);

// Propagate exception to caller.

throw ex;

} finally {

// Reset common introspection caches in Spring’s core, since we

// might not ever need metadata for singleton beans anymore…

resetCommonCaches();

contextRefresh.end();

}

}

}

这里有非常多的步骤,上下文对象主要的bean也是在这里进行处理的,具体的说明可以看注释

@Override

public final void refresh() throws BeansException, IllegalStateException {

try {

super.refresh();

}

catch (RuntimeException ex) {

WebServer webServer = this.webServer;

if (webServer != null) {

webServer.stop();

}

throw ex;

}

}

主要还是调用父类方法,没有什么特殊的

run方法/第七步:spring容器后置处理 afterRefresh()

protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {

}

这是一个空的方法

run方法启动后

主要做如下几件事情:

发出启动结束事件

执行实现ApplicationRunner、CommandLineRunner的run方法

发布应用程序已启动(ApplicationStartedEvent)事件

run方法异常处理

如果run方法的处理过程中发生异常,则对exitCode进行相应处理

private void handleRunFailure(ConfigurableApplicationContext context, Throwable exception,

SpringApplicationRunListeners listeners) {

try {

try {

handleExitCode(context, exception);

if (listeners != null) {

listeners.failed(context, exception);

}

} finally {

reportFailure(getExceptionReporters(context), exception);

if (context != null) {

context.close();

}

}

} catch (Exception ex) {

logger.warn(“Unable to close ApplicationContext”, ex);

}

ReflectionUtils.rethrowRuntimeException(exception);

}

至此,所有SpringBoot的启动流程已经完成,你的项目也顺利的跑起来了

原文链接:https://www.cnblogs.com/lanblogs/p/14888244.html

相关文章
|
3月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
1396 0
|
2月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
2月前
|
XML JSON Java
【SpringBoot(三)】从请求到响应再到视图解析与模板引擎,本文带你领悟SpringBoot请求接收全流程!
Springboot专栏第三章,从请求的接收到视图解析,再到thymeleaf模板引擎的使用! 本文带你领悟SpringBoot请求接收到渲染的使用全流程!
253 3
|
3月前
|
Java 数据库 数据安全/隐私保护
Spring Boot四层架构深度解析
本文详解Spring Boot四层架构(Controller-Service-DAO-Database)的核心思想与实战应用,涵盖职责划分、代码结构、依赖注入、事务管理及常见问题解决方案,助力构建高内聚、低耦合的企业级应用。
911 1
|
5月前
|
机器学习/深度学习 XML Java
【spring boot logback】日志logback格式解析
在 Spring Boot 中,Logback 是默认的日志框架,它支持灵活的日志格式配置。通过配置 logback.xml 文件,可以定义日志的输出格式、日志级别、日志文件路径等。
927 5
|
5月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
485 3
|
9月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
918 29
|
9月前
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
391 4
|
9月前
|
JavaScript 算法 前端开发
JS数组操作方法全景图,全网最全构建完整知识网络!js数组操作方法全集(实现筛选转换、随机排序洗牌算法、复杂数据处理统计等情景详解,附大量源码和易错点解析)
这些方法提供了对数组的全面操作,包括搜索、遍历、转换和聚合等。通过分为原地操作方法、非原地操作方法和其他方法便于您理解和记忆,并熟悉他们各自的使用方法与使用范围。详细的案例与进阶使用,方便您理解数组操作的底层原理。链式调用的几个案例,让您玩转数组操作。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~

热门文章

最新文章

推荐镜像

更多
  • DNS