使用了很长时间的springboot了,一直都知道它简单易用,简化了框架的搭建过程,但是还是不知道它是如何启动的,今天就跟着springboot的源码,去探探这其中的奥妙

    以下是spring应用的启动:

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
//加载配置文件
System.setProperty("spring.config.location","classpath:db_config.properties,classpath:mq.properties");
SpringApplication.run(Application.class, args); }
}

然后我们跟着Run方法进去

public ConfigurableApplicationContext run(String... args) {
//一开始就是一个StopWatch 类,这个类的主要作用是记录容器启动用时
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
this.configureHeadlessProperty();
SpringApplicationRunListeners listeners = this.getRunListeners(args);
listeners.starting(); try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
Banner printedBanner = this.printBanner(environment);
context = this.createApplicationContext();
new FailureAnalyzers(context);
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
this.refreshContext(context);
this.afterRefresh(context, applicationArguments);
listeners.finished(context, (Throwable)null);
stopWatch.stop();
if(this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
} return context;
} catch (Throwable var9) {
this.handleRunFailure(context, listeners, (FailureAnalyzers)analyzers, var9);
throw new IllegalStateException(var9);
}
}

第一步:可以看到,一开始是一个StopWatch类,该类的作用比较单一,就是记录springboot的启动用时,我们启动springboot完成后会在控制台springboot启动所花的时间,就是由它来完成的

//然后我们看看this.createApplicationContext()方法:
private void configureHeadlessProperty() {
System.setProperty("java.awt.headless", System.getProperty("java.awt.headless", Boolean.toString(this.headless)));
}
//主要是用来设置系统属性,具体这个属性有何作用,有待探究

第二步:创建SpringApplicationRunListeners

//接下来我们看看springboot是如何去初始化监听器SpringApplicationRunListeners的。this.getRunListeners(args)方法如下:
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class[]{SpringApplication.class, String[].class};
return new SpringApplicationRunListeners(logger, this.getSpringFactoriesInstances(SpringApplicationRunListener.class, types, new Object[]{this, args}));
}
//利用传入的参数args去创建一个SpringApplicationRunListeners实例,此处会去获取一个SpringFactory的实例,下面我们重点看看是如何来获取该SpringFactory实例的
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
//首先获取当前线程的类加载器,然后通过SpringFactoriesLoader去加载SpringApplicationRunListener这个类,接下来看看在加载SpringApplicationRunListener这个spring应用的运行监听器时做了什么事情
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
String factoryClassName = factoryClass.getName(); try {
Enumeration ex = classLoader != null?classLoader.getResources("META-INF/spring.factories"):ClassLoader.getSystemResources("META-INF/spring.factories");
ArrayList result = new ArrayList(); while(ex.hasMoreElements()) {
URL url = (URL)ex.nextElement();
Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
String factoryClassNames = properties.getProperty(factoryClassName);
result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
} return result;
} catch (IOException var8) {
throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() + "] factories from location [" + "META-INF/spring.factories" + "]", var8);
}
}
//首先通过当前线程的类加载器获取Springboot项目META-INF下面的spring.factories文件,找到该文件,我们可以看到该文件中配置了PropertySource Loaders(属性来源加载)、运行监听器EventPublishingRunListener、运用上下文初始化工具、应用监听器等等一系列的自动化配置,都是从这里加载到应用中来的。加载完成之后,SpringFactory通过反射来获取这些类的实例,然后放入到SpringApplicationRunListeners中,至此,SpringApplicationRunListeners初始化完成。这里,我们看看SpringApplicationRunListeners中有些什么,源码如下:
class SpringApplicationRunListeners {
private final Log log;
private final List<SpringApplicationRunListener> listeners; SpringApplicationRunListeners(Log log, Collection<? extends SpringApplicationRunListener> listeners) {
this.log = log;
this.listeners = new ArrayList(listeners);
}
}
//有一个log,用于记录日志,然后就是一个final的list,里面就是之前初始化时从配置中获取的各种listener
再次回顾一下SpringApplicationRunListeners的创建过程:首先获取当前线程的ClassLoader,然后通过SpringFactoriesLoader去加载Springboot项目中META-INF文件夹下的spring.factories配置文件,之后通过反射获取相关listener实例,存储到SpringApplicationRunListeners的list属性中,由此完成SpringApplicationRunListeners的初始化过程

第三步:启动SpringApplicationRunListeners中所有的监听器

第四步:环境准备

第五步:打印Banner

第六步:创建上下文

springboot启动过程的更多相关文章

  1. SpringBoot启动过程原理

    最近这两年springboot突然火起来了,那么我们就来看看springboot的运行原理. 一.springboot的三种启动方式: 1.运行带有main方法的2.通过命令 Java -jar命令3 ...

  2. Spring Boot 学习笔记一(SpringBoot启动过程)

    SpringBoot启动 Spring Boot通常有一个名为*Application的入口类,在入口类里有一个main方法,这个main方法其实就是一个标准的java应用的入口方法. 在main方法 ...

  3. (四)SpringBoot启动过程的分析-预处理ApplicationContext

    -- 以下内容均基于2.1.8.RELEASE版本 紧接着上一篇(三)SpringBoot启动过程的分析-创建应用程序上下文,本文将分析上下文创建完毕之后的下一步操作:预处理上下文容器. 预处理上下文 ...

  4. (三)SpringBoot启动过程的分析-创建应用程序上下文

    -- 以下内容均基于2.1.8.RELEASE版本 紧接着上一篇(二)SpringBoot启动过程的分析-环境信息准备,本文将分析环境准备完毕之后的下一步操作:ApplicationContext的创 ...

  5. (一)SpringBoot启动过程的分析-启动流程概览

    -- 以下内容均基于2.1.8.RELEASE版本 通过粗粒度的分析SpringBoot启动过程中执行的主要操作,可以很容易划分它的大流程,每个流程只关注重要操作为后续深入学习建立一个大纲. 官方示例 ...

  6. (五)SpringBoot启动过程的分析-刷新ApplicationContext

    -- 以下内容均基于2.1.8.RELEASE版本 紧接着上一篇[(四)SpringBoot启动过程的分析-预处理ApplicationContext] (https://www.cnblogs.co ...

  7. springboot启动过程(1)-初始化

    1   springboot启动时,只需要调用一个类前面加了@SpringBootApplication的main函数,执行SpringApplication.run(DemoApplication. ...

  8. SpringBoot启动过程原理(转)

    1.1 Springboot启动: @SpringBootApplication public class ServerApplication { public static void main(St ...

  9. (二)SpringBoot启动过程的分析-环境信息准备

    -- 以下内容均基于2.1.8.RELEASE版本 由上一篇SpringBoot基本启动过程的分析可以发现在run方法内部启动SpringBoot应用时采用多个步骤来实现,本文记录启动的第二个环节:环 ...

随机推荐

  1. PMP项目管理——项目范围管理-规划范围管理

    规划范围管理是为记录如何定义.确认和控制项目范围及产品范围,而创建范围管理计划的过程.主要作用是,在整个项目期间对如何管理范围提供指南和方向.制定范围管理计划和细化项目范围始于对下列信息的分析:项目章 ...

  2. sql准确判断某个ip

    问题:如图 当我执行sql要准确查找某个IP是属于哪个库室时候,我刚开始是这样写的 select * from Definition_Read_Room where HFIP like '%172.2 ...

  3. Soldier and Number Game-素数筛

    Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and giv ...

  4. 2019 牛客多校第一场 D Parity of Tuples

    题目链接:https://ac.nowcoder.com/acm/contest/881/D 看此博客之前请先参阅吕凯飞的论文<集合幂级数的性质与应用及其快速算法>,论文中很多符号会被本文 ...

  5. msSql Server 修复数据库

    --rz要替换为修复数据库DBCC CHECKTABLE ('rz'); use master declare @databasename varchar(255) set @databasename ...

  6. python学习7—函数定义、参数、递归、作用域、匿名函数以及函数式编程

    python学习7—函数定义.参数.递归.作用域.匿名函数以及函数式编程 1. 函数定义 def test(x) # discription y = 2 * x return y 返回一个值,则返回原 ...

  7. 归档和解档配合NSFile存储数据

    NSString *Name = @"yc"; //第一个常量NSDocumentDirectory表示正在查找沙盒Document目录的路径(如果参数为NSCachesDirec ...

  8. SQL链接EXCEL操作

    Sub CopyData_5() Set Cnn = CreateObject("ADODB.Connection")With Cnn.Provider = "micro ...

  9. spark安装及配置

    windows下spark的安装与配置教程 Windows下安装spark windows下搭建spark环境出现ChangeFileModeByMask error (3): ??????????? ...

  10. C++ 系列:随机数

    C++中没有自带的random函数,要实现随机数的生成就需要使用rand()和srand().不过,由于rand()的内部实现是用线性同余法做的,所以生成的并不是真正的随机数,而是在一定范围内可看为随 ...