厉害了!SpringBoot是如何动起来的!
程序入口
SpringApplication.run(BeautyApplication.class, args);
执行此方法来加载整个SpringBoot的环境。
1. 从哪儿开始?
SpringApplication.java
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
//...
}
调用SpringApplication.java 中的 run 方法,目的是加载Spring Application,同时返回 ApplicationContext。
2. 执行了什么?
2.1 计时
记录整个Spring Application的加载时间!
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// ...
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
2.2 声明
// 声明 ApplicationContext
ConfigurableApplicationContext context = null;
// 声明 一个异常报告集合
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
2.3 指定程序运行模式
指定 java.awt.headless,默认是true 一般是在程序开始激活headless模式,告诉程序,现在你要工作在Headless mode下,就不要指望硬件帮忙了,你得自力更生,依靠系统的计算能力模拟出这些特性来。
private void configureHeadlessProperty() {
System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty(
SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
}
2.4 配置监听并发布应用启动事件
SpringApplicationRunListener 负责加载 ApplicationListener事件。
SpringApplicationRunListeners listeners = getRunListeners(args);
// 开始
listeners.starting();
// 处理所有 property sources 配置和 profiles 配置,准备环境,分为标准 Servlet 环境和标准环境
ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments);
// 准备应用上下文
prepareContext(context, environment, listeners, applicationArguments,printedBanner);
// 完成
listeners.started(context);
// 异常
handleRunFailure(context, ex, exceptionReporters, listeners);
// 执行
listeners.running(context);
getRunListeners 中根据 type = SpringApplicationRunListener.class 去拿到了所有的 Listener 并根据优先级排序。
对应的就是 META-INF/spring.factories 文件中的 org.springframework.boot.SpringApplicationRunListener=org.springframework.boot.context.event.EventPublishingRunListener
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
在 ApplicationListener 中 , 可以针对任何一个阶段插入处理代码。
public interface SpringApplicationRunListener {
/**
* Called immediately when the run method has first started. Can be used for very
* early initialization.
*/
void starting();
/**
* Called once the environment has been prepared, but before the
* {@link ApplicationContext} has been created.
* @param environment the environment
*/
void environmentPrepared(ConfigurableEnvironment environment);
/**
* Called once the {@link ApplicationContext} has been created and prepared, but
* before sources have been loaded.
* @param context the application context
*/
void contextPrepared(ConfigurableApplicationContext context);
/**
* Called once the application context has been loaded but before it has been
* refreshed.
* @param context the application context
*/
void contextLoaded(ConfigurableApplicationContext context);
/**
* The context has been refreshed and the application has started but
* {@link CommandLineRunner CommandLineRunners} and {@link ApplicationRunner
* ApplicationRunners} have not been called.
* @param context the application context.
* @since 2.0.0
*/
void started(ConfigurableApplicationContext context);
/**
* Called immediately before the run method finishes, when the application context has
* been refreshed and all {@link CommandLineRunner CommandLineRunners} and
* {@link ApplicationRunner ApplicationRunners} have been called.
* @param context the application context.
* @since 2.0.0
*/
void running(ConfigurableApplicationContext context);
/**
* Called when a failure occurs when running the application.
* @param context the application context or {@code null} if a failure occurred before
* the context was created
* @param exception the failure
* @since 2.0.0
*/
void failed(ConfigurableApplicationContext context, Throwable exception);
}
3. 每个阶段执行的内容
3.1 listeners.starting();
在加载Spring Application之前执行,所有资源和环境未被加载。
3.2 prepareEnvironment(listeners, applicationArguments);
创建 ConfigurableEnvironment;将配置的环境绑定到Spring Application中;
private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
listeners.environmentPrepared(environment);
bindToSpringApplication(environment);
if (this.webApplicationType == WebApplicationType.NONE) {
environment = new EnvironmentConverter(getClassLoader())
.convertToStandardEnvironmentIfNecessary(environment);
}
ConfigurationPropertySources.attach(environment);
return environment;
}
3.3 prepareContext
配置忽略的Bean;
private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) {
if (System.getProperty(
CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) {
Boolean ignore = environment.getProperty("spring.beaninfo.ignore",
Boolean.class, Boolean.TRUE);
System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME,
ignore.toString());
}
}
打印日志-加载的资源
Banner printedBanner = printBanner(environment);
根据不同的WebApplicationType创建Context
context = createApplicationContext();
3.4 refreshContext
支持定制刷新
/**
* Register a shutdown hook with the JVM runtime, closing this context
* on JVM shutdown unless it has already been closed at that time.
* <p>This method can be called multiple times. Only one shutdown hook
* (at max) will be registered for each context instance.
* @see java.lang.Runtime#addShutdownHook
* @see #close()
*/
void registerShutdownHook();
3.5 afterRefresh
刷新后的实现方法暂未实现
/**
* Called after the context has been refreshed.
* @param context the application context
* @param args the application arguments
*/
protected void afterRefresh(ConfigurableApplicationContext context,
ApplicationArguments args) {
}
3.6 listeners.started(context);
到此为止, Spring Application的环境和资源都加载完毕了;发布应用上下文启动完成事件;执行所有 Runner 运行器 - 执行所有 ApplicationRunner 和 CommandLineRunner 这两种运行器。
// 启动
callRunners(context, applicationArguments);
3.7 listeners.running(context);
触发所有 SpringApplicationRunListener 监听器的 running 事件方法
(完)
本人免费整理了Java高级资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo高并发分布式等教程,一共30G,需要自己领取。
传送门:https://mp.weixin.qq.com/s/osB-BOl6W-ZLTSttTkqMPQ
厉害了!SpringBoot是如何动起来的!的更多相关文章
- SpringBoot是如何动起来的
SpringBoot是如何动起来的 程序入口 SpringApplication.run(BeautyApplication.class, args); 执行此方法来加载整个SpringBoot的环境 ...
- 尚硅谷springboot学习35-启动原理
先列出几个重要的事件回调机制 配置在META-INF/spring.factories ApplicationContextInitializer SpringApplicationRunListen ...
- 尚硅谷springboot学习14-自动配置原理
配置文件能配置哪些属性 配置文件能配置的属性参照 自动配置的原理 1).SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration 2).@Ena ...
- SpringBoot是如何动起来的?
程序入口 SpringApplication.run(BeautyApplication.class, args); 执行此方法来加载整个SpringBoot的环境. 1. 从哪儿开始? Spring ...
- 2.SpringBoot HelloWorld详解
1.POM文件 父项目 <parent> <groupId>org.springframework.boot</groupId> <artifactId> ...
- springboot Hello World探究
Hello World探究1.POM文件1.父项目 <parent> <groupId>org.springframework.boot</groupId> ...
- SpringBoot入门(简单详细教程)
Spring Boot 简介 简化Spring应用开发的一个框架:整个Spring技术栈的一个大整合:J2EE开发的一站式解决方案: 微服务 martin fowler:微服务:架构风格(服务微化): ...
- springboot核心技术(一)-----入门、配置
Hello World 1.创建一个maven工程:(jar) 2.导入spring boot相关的依赖 <parent> <groupId>org.springframewo ...
- 1、spring boot入门
1.Spring Boot 简介 简化Spring应用开发的一个框架: 整个Spring技术栈的一个大整合: J2EE开发的一站式解决方案: 2.微服务 2014,martin fowler 微服务: ...
随机推荐
- mysql中date与datetime的区别
date类型可用于需要一个日期值而不需要时间部分时.MySQL 以 'YYYY-MM-DD' 格式检索与显示date值.支持的范围是 '1000-01-01' 到'9999-12-31'. datet ...
- sqlserver数据将多个表或视图的数据合并到一个表或视图里的sql语句
create view dbo.V_ZDUser_DDasselect * from dbo.V_ZDUser_DD1 union all select * from dbo.V_ZDUser_DD2 ...
- HDU 1372 Knight Moves(bfs)
嗯... 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372 这是一道很典型的bfs,跟马走日字一个道理,然后用dir数组确定骑士可以走的几个方向, ...
- Centos 下安装php
1 从php 官网下载源安装包 http://php.net/downloads.php // 安装php 扩展 2 yum install libxml2 libxml2-devel openssl ...
- 多项式输出 (0)<P2009_1>
多项式输出 (poly.pas/c/cpp) [问题描述] 一元n次多项式可用如下的表达式表示: 其中,称为i次项,ai称为i次项的系数.给出一个一元多项式各项的次数和系数,请按照如下规定的格式要求输 ...
- PAT T1022 Werewolf
暴力搜索加剪枝~ #include<bits/stdc++.h> using namespace std; ; int a[maxn]; bool visit[maxn]; vector& ...
- 十三 Spring的通知类型,切入表达式写法
Spring中通知类型: 前置通知:目标方法执行之前进行操作,可以获得切入点信息 后置通知: 目标方法执行之后进行操作,可以获得方法的返回值 环绕通知:在目标方法执行之前和之后进行操作,可以终止目标方 ...
- mysql 连接数据库时时区报错
1.url: jdbc:mysql://192.168.0.101:3306/testdb?serverTimezone=UTC,在连接字符后面添加时区设置 2.使用navicat或者直接使用mysq ...
- ubuntu---CUDA 安装注意点总结
安装CUDA前的基础准备: 1.查看内核.gcc版本并记住. 最好 禁止内核更新,以防止以后工作中意外的系统更新使内核自动更新了,与驱动版本不兼容了. 2.禁用 nouveau驱动. 3.多下 ...
- Java基础 -2.3
浮点数类型 所有的数据类型进行自动转型的时候都是由小类型到大类型进行自动转换处理.默认的类型为double,但是也可以定义位数相对较少的float变量 ,此时从赋值的时候就必须采用强制类型转换 pub ...