欢迎来到电脑知识学习网,专业的电脑知识大全学习平台!

手机版

springboot启动流程详解(springboot三种启动方法)

操作系统 发布时间:2022-06-12 09:28:17

一切从SpringApplication.run()开始,最终返回一个ConfigurableApplicationContext

springboot启动流程详解(springboot三种启动方法)(1)

构造了一个SpringApplication对象,然后调用它的run方法。下面看下构造方法都做了什么

springboot启动流程详解(springboot三种启动方法)(2)

1、推断Web应用类型(WebApplicationType),本例中是SERVLET

2、设置 Bootstrapper、ApplicationContextInitializer 和 ApplicationListener

3、推断main方法

注意到,在设置 Bootstrapper、ApplicationContextInitializer 和 ApplicationListener 时,都调用了同一个方法getSpringFactoriesInstances

springboot启动流程详解(springboot三种启动方法)(3)

springboot启动流程详解(springboot三种启动方法)(4)

springboot启动流程详解(springboot三种启动方法)(5)

从所有 META-INF/spring.factories 文件中加载,并查找指定名称的的值

springboot启动流程详解(springboot三种启动方法)(6)

回到之前的构造方法那里,现在我们知道设置的Bootstrapper、ApplicationContextInitializer、ApplicationListener是从哪儿来的了,原来是在META-INF/spring.factories中配置的。查找指定key对应的值,然后实例化它们,并返回一个List

springboot启动流程详解(springboot三种启动方法)(7)

接下来,重头戏,调用run方法

springboot启动流程详解(springboot三种启动方法)(8)

重点看try里面的内容

首先是启动监听器来监听启动过程,这里再一次调用了熟悉的getSpringFactoriesInstances

springboot启动流程详解(springboot三种启动方法)(9)

然后,将main方法中传的参数包装成ApplicationArguments对象

紧接着,创建并配置环境,返回一个ConfigurableEnvironment对象,由于本例中是SERVLET,所以创建的是StandardServletEnvironment

然后,打印Banner

创建ApplicationContext,所有基于Spring的项目启动过程都是创建ApplicationContext

springboot启动流程详解(springboot三种启动方法)(10)

这里创建的ConfigurableApplicationContext是AnnotationConfigServletWebServerApplicationContext

有了ApplicationContext,紧接着要配置ApplicationContext

springboot启动流程详解(springboot三种启动方法)(11)

加载所有的source(其实就是class),然后实例化

springboot启动流程详解(springboot三种启动方法)(12)

这里就是一个,就是启动类

springboot启动流程详解(springboot三种启动方法)(13)

springboot启动流程详解(springboot三种启动方法)(14)

接下来,刷新容器

springboot启动流程详解(springboot三种启动方法)(15)

springboot启动流程详解(springboot三种启动方法)(16)

最终是调用Spring的applicationContext.refresh(),又看到了熟悉的一幕

springboot启动流程详解(springboot三种启动方法)(17)

最后还留了一个入口,回调子容器的onRefresh()

springboot启动流程详解(springboot三种启动方法)(18)

Spring MVC的启动是创建父子两个WebApplicationContext

在刷新容器之后,所有的Bean都已经实例化完成

springboot启动流程详解(springboot三种启动方法)(19)

afterRefresh什么也没做

最后是回调Runner,回调所有的ApplicationRunner和CommandLineRunner

springboot启动流程详解(springboot三种启动方法)(20)

至此,Spring Boot启动完成

回顾一下,

1、推断Web应用类型

2、设置Bootstrapper、ApplicationContextInitializer、ApplicationListener

3、推断main方法

4、创建并配置环境Environment

5、打印Banner

6、创建并配置ApplicationContext

7、刷新ApplicationContext(此处交由Spring处理,调用Spring的refresh()方法)实例化所有的bean

8、回调所有的ApplicationRunner和CommandLineRunner


责任编辑:电脑知识学习网

操作系统