springboot2.0启动原理源码剖析

源于蚂蚁课堂的学习,点击这里查看

1.maven依赖 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

2.启动源码流程

 

具体来剖析这三个方法
// 判断启动类型
this.webApplicationType = WebApplicationType.deduceFromClasspath();

// 加载所有jar中的spring.factories文件
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

// 加载配置文件的监听器
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
WebApplicationType.deduceFromClasspath()

 

setInitializers

setListeners

 

生成springApplication对象后,开始执行run方法

run方法启动重点分析

// 获取所有启动的监听器
SpringApplicationRunListeners listeners = getRunListeners(args);

// 环境启动的准备工作
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); 

// 自定义轮播图
Banner printedBanner = printBanner(environment);

// 创建boot的上下文
context = createApplicationContext();

// 预加载上下文
prepareContext(context, environment, listeners, applicationArguments, printedBanner);

// 刷新上下文
refreshContext(context);

// 后置处理
afterRefresh(context, applicationArguments);+

// 上下文启动后,监听器回调
listeners.started(context);

// 监听器回调后,开始运行所有监听器
listeners.running(context);
getRunListeners

prepareEnvironment

printBanner

createApplicationContext

prepareContext

refreshContext

afterRefresh

listeners.started

listeners.running

 3.注解源码剖析

 

 

 

这两个类一个是springMVC的核心类,一个是servlet的核心类

 

 

4.总结 

@SpringbootAplication
1.@SpringbootAplication底层可拆分为三个注解@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan
2.@SpringBootConfiguration是对spring注解@Configuration的包装
3.@ComponentScan定义 了默认的扫包范围为当前启动类所在包下的所有类
4.@EnableAutoConfiguration中主要引入了AutoConfigurationImportSelector这个类选择器
5.AutoConfigurationImportSelector中将org.springframework.boot.autoconfigure这个依赖jar中的spring.factories文件中的类全部加载
6.spring.factories中定义了很多配置类,其中包括DispatcherServletAutoConfiguration(springMVC核心类)和ServletWebServerFactoryAutoConfiguration(容器类)
7.ServletWebServerFactoryAutoConfiguration中 通过@Import将三种web容器注入IOC:EmbeddedTomcat、EmbeddedJetty和EmbeddedUndertow
8.以默认的tomcat为例,IOC:EmbeddedTomcat中通过@Bean的方式将TomcatServletWebServerFactory注入IOC
9.TomcatServletWebServerFactory的getWebServer会创建tomcat服务器,并将本地class文件交由其运行管理

启动运行流程
1.springboot启动时,会先创建sprinApplication对象,再执行其run方法
2.创建springApplication对象时会先判断当前启动时哪一类型的WebApplicationType
3.通过setInitializers和setListeners会将所有jar中/resources/META-INF/下的spring.factories文件中的类注入IOC
4.执行run方法时,会开启计时
5.获取所有的启动listener
6.将环境加载
7.打印轮播图
8.创建springboot的上下文对象
9.装配上下文
10.刷新上下文(和spring注解方式启动原理一致)
11.刷新之后的后续操作(扩展)
12.发布订阅的方式广播通知listener,context要启动了
13.发布订阅的方式广播通知listener,context已经启动
原创文章 148 获赞 258 访问量 11万+

猜你喜欢

转载自blog.csdn.net/yxh13521338301/article/details/105433157
今日推荐