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 声明

指定 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 事件方法

SpringBoot是如何动起来的的更多相关文章

  1. 尚硅谷springboot学习35-启动原理

    先列出几个重要的事件回调机制 配置在META-INF/spring.factories ApplicationContextInitializer SpringApplicationRunListen ...

  2. 尚硅谷springboot学习14-自动配置原理

    配置文件能配置哪些属性 配置文件能配置的属性参照 自动配置的原理 1).SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration 2).@Ena ...

  3. SpringBoot是如何动起来的?

    程序入口 SpringApplication.run(BeautyApplication.class, args); 执行此方法来加载整个SpringBoot的环境. 1. 从哪儿开始? Spring ...

  4. 厉害了!SpringBoot是如何动起来的!

    程序入口 SpringApplication.run(BeautyApplication.class, args); 执行此方法来加载整个SpringBoot的环境. 1. 从哪儿开始? Spring ...

  5. 2.SpringBoot HelloWorld详解

    1.POM文件 父项目 <parent> <groupId>org.springframework.boot</groupId> <artifactId> ...

  6. springboot Hello World探究

    Hello World探究1.POM文件1.父项目 <parent>     <groupId>org.springframework.boot</groupId> ...

  7. SpringBoot入门(简单详细教程)

    Spring Boot 简介 简化Spring应用开发的一个框架:整个Spring技术栈的一个大整合:J2EE开发的一站式解决方案: 微服务 martin fowler:微服务:架构风格(服务微化): ...

  8. springboot核心技术(一)-----入门、配置

    Hello World 1.创建一个maven工程:(jar) 2.导入spring boot相关的依赖 <parent> <groupId>org.springframewo ...

  9. 1、spring boot入门

    1.Spring Boot 简介 简化Spring应用开发的一个框架: 整个Spring技术栈的一个大整合: J2EE开发的一站式解决方案: 2.微服务 2014,martin fowler 微服务: ...

随机推荐

  1. [Git]2018-10 解决git cmd中文乱码问题

    2018年10月12日 莫名其妙出现cmd下git log中文乱码问题,显示一堆<E4><A8>之类的乱码.git bash却一切正常. 怀疑是Windows系统升级出现的不兼 ...

  2. SpringInAction学习笔记(一):核心概念

    Spring自带了多种应用上下文 AnnotationConfigApplicationContext:从一个或多个java配置类中加载应用上下文 AnnotationConfigWebApplica ...

  3. Python数据可视化编程实战pdf

    Python数据可视化编程实战(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1vAvKwCry4P4QeofW-RqZ_A 提取码:9pcd 复制这段内容后打开百度 ...

  4. Ubuntu下编译SqlCipher以及解密微信数据库EnMicroMsg.db过程和坑

    wget https://codeload.github.com/sqlcipher/sqlcipher/zip/v3.4.2 ./configure --enable-tempstore=yes C ...

  5. Luogu 3384 【模板】树链剖分

    题目描述 如题,已知一棵包含N个结点的树(连通且无环),每个节点上包含一个数值,需要支持以下操作: 操作1: 格式: 1 x y z 表示将树从x到y结点最短路径上所有节点的值都加上z 操作2: 格式 ...

  6. js实现八皇后,回溯法

    八皇后问题:将八个皇后摆在一张8*8的国际象棋棋盘上,使每个皇后都无法吃掉别的皇后,一共有多少种摆法? 两个皇后不能同时在同一行,同一列,和斜对角线的位置上,使用回溯法解决. 从第一行选个位置开始放棋 ...

  7. 4.20 Linux01

    2019-4-20 21:04:14 day102linux 开始认真学习Linux ,因为服务器部署还是得会Linux 开始整理一下笔记 等把Linux全部学完后 然后写个文章整理一下! Linux ...

  8. 你不知道的JS之作用域和闭包(一)什么是作用域?

    原文:你不知道的js系列 什么是作用域(Scope)? 作用域 是这样一组规则——它定义了如何存放变量,以及程序如何找到之前定义的变量. 编译器原理 JavaScript 通常被归类为动态语言或者解释 ...

  9. Reactjs组件中的方法为什么绑定this?

    前言:Reactjs中的定义的方法其实是基于实例的原型方法:es6默认严格模式   问题:在Reactjs组件中写入以下代码,那么执行结果会是什么呢? ··· 结果是这样的: 对的,你没看错,不是do ...

  10. LAMP构架搭建论坛

    安装MYSQL数据库服务程序       LAMP动态网站部署架构是一套由Linux+Nginx+MYSQL+PHP组成的动态网站系统解决方案,具有免费.高效.扩展性强且资源消耗低等优良特性.使用手工 ...