一、启动流程

  1. 创建SpringApplication对象
public class SpringApplication {

    public SpringApplication(Class... primarySources) {
this((ResourceLoader)null, primarySources);
} public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
this.sources = new LinkedHashSet();
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = new HashSet();
this.isCustomEnvironment = false;
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
// 保存主配置类
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
// 判断当前是否一个web应用
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 从类路径下找到META-INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起来。
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 从类路径下找到META-INF/spring.factories配置的所有ApplicationListener
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
//从多个配置类中找到有main方法的主配置类
this.mainApplicationClass = this.deduceMainApplicationClass();
}
  1. 运行run方法
    public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
this.configureHeadlessProperty();
// 获取SpringApplicationRunListener; 从类路径下META-INF/spring.factories获取
SpringApplicationRunListeners listeners = this.getRunListeners(args);
// 回调所有的获取SpringApplicationRunListener.starting()方法
listeners.starting(); Collection exceptionReporters;
try {
// 封装命令行参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 准备环境
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
// 创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准备完成
Banner printedBanner = this.printBanner(environment);
// 创建ApplicationContext;决定创建web的IOC还是普通的IOC
context = this.createApplicationContext();
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
// 准备上下文环境;将environment保存到IOC中,而且applyInitializers();
// 而且applyInitializers():回调之前保存的所有ApplicationContextInitializer的initialize方法
// 回调所有的SpringApplicationRunListener的contextPrepared();
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded();
// 扫描容器;IOC容器初始化(如果是web应用还会创建嵌入的Tomcat);
// 扫描,创建,加载所有组件的地方(配置类,组件,自动配置)
this.refreshContext(context);
// 从IOC容器中获取所有的ApplicationRunner和CommandLineRunner进行回调
// ApplicationRunner先回调,CommandLineRunner再回调
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
} listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
} try {
listeners.running(context);
// 整个SpringBoot应用启动完成以后返回启动的IOC容器
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
  1. 事件监听机制

    需要配置在META-INF/spring.factories中的事件监听器。

    ApplicationContextInitializer
public class CustomApplicationContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> { @Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
System.out.println("ApplicationContextInitializer.....initialize");
}
}

SpringApplicationRunListener

public class CustomSrpingApplicationRunListener implements SpringApplicationRunListener {

    // 必须有的构造器
public CustomSrpingApplicationRunListener(SpringApplication application,String[] args){ }
@Override
public void starting() {
System.out.println("SpringApplicationRunListener...starting....");
} @Override
public void environmentPrepared(ConfigurableEnvironment environment) {
Object o = environment.getSystemEnvironment().get("os.name");
System.out.println("SpringApplicationRunListener...environmentPrepared...."+o);
} @Override
public void contextPrepared(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener..contextPrepared");
} @Override
public void contextLoaded(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener..contextLoaded");
} @Override
public void started(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener..started");
} @Override
public void running(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener..running");
} @Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
System.out.println("SpringApplicationRunListener..failed");
} }

配置(META-INF/spring.factories)

org.springframework.context.ApplicationContextInitializer=com.desperado.demo.CustomApplicationContextInitializer
org.springframework.boot.SpringApplicationRunListener=com.desperado.demo.CustomSrpingApplicationRunListener

只需要放在IOC容器中的监听器。

ApplicationRunner

@Component
public class CustomApplicationRunner implements ApplicationRunner { @Override
public void run(ApplicationArguments args) {
System.out.println("ApplicationRunner ... run....");
}
}

CommandLineRunner

@Component
public class CustomCommandLineRunner implements CommandLineRunner { @Override
public void run(String... args) {
System.out.println("commandLineRunner ... run ...");
}
}

二、自定义starter

  1. 要使用到的注解

    @Configuration 指定类是一个配置类

    @ConditionalOnXXX 在指定条件成立的情况下自动配置生效、

    @AutoConfigureAfter 在特定自动装配class之后(指定自动配置类的顺序)

    @AutoConfigureBefore 在特定自动装配class之前(指定自动配置类的顺序)

    @AutoConfigureOrder 指定顺序

    @Bean 给容器中添加组件

    @ConfigurationPropertie 结合相关xxxProperties类来绑定相关的配置。

    @EnableConfigurationProperties 让xxxProperties生效加入到容器中。

  2. 加载方式

    自动配置类要能加载,将需要启动就加载的自动配置类,配置在META-INF/spring.factories文件中。

  3. 启动器模式

    启动器只用来做依赖导入,专门写一个自动配置模块。启动器依赖自动配置,使用时只需要引入启动器(starter)。

  4. 启动器规则

    启动器就是个空jar文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他库。

命名规范:

- 推荐使用以下命名规范

- 官方命名空间

 - 前缀:spring-boot-starter-

 - 模式:spring-boot-starter-模块名

- 自定义命名空间

  - 后缀:-spring-boot-starter

  - 模式:模块名-spring-boot-starter

  1. 编写一个启动器模块

    1). 启动器模块
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.desperado.starter</groupId>
<artifactId>desperado-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 启动器 -->
<dependencies>
<!-- 引入自动配置模块 -->
<dependency>
<groupId>com.desperado.starter</groupId>
<artifactId>desperado-spring-boot-starter-autoconfigurer</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency> </dependencies> </project>

2). 自动配置模块

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.desperado.starter</groupId>
<artifactId>desperado-spring-boot-starter-autoconfigurer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <!-- 引入spring-boot-starter;所有starter的基本配置 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> </dependencies> </project>

3). 编写配置文件类

@ConfigurationProperties(prefix = "desperado.custom")
public class CustomProperties { private String prefix; private String suffix; public String getPrefix() {
return prefix;
} public void setPrefix(String prefix) {
this.prefix = prefix;
} public String getSuffix() {
return suffix;
} public void setSuffix(String suffix) {
this.suffix = suffix;
}
}

4). 进行配置文件的处理

public class CustomService {
CustomProperties customProperties; public CustomProperties getCustomProperties(){
return customProperties;
} public void setCustomProperties(CustomProperties customProperties){
this.customProperties = customProperties;
} public String sayHello(String name){
return customProperties.getPrefix()+"-"+name+customProperties.getSuffix();
}
}

5). 编写自动配置类

@ConditionalOnWebApplication
@EnableConfigurationProperties(CustomProperties.class)
public class CustomServiceAutoConfiguration { @Autowired
CustomProperties customProperties; @Bean
public CustomService customService(){
CustomService customService = new CustomService();
customService.setCustomProperties(customProperties);
return customService;
}
}

SpringBoot的启动配置原理的更多相关文章

  1. SpringBoot嵌入式Servlet配置原理

    SpringBoot嵌入式Servlet配置原理 SpringBoot修改服务器配置 配置文件方式方式修改,实际修改的是ServerProperties文件中的值 server.servlet.con ...

  2. 【SpringBoot1.x】SpringBoot1.x 启动配置原理 和 自定义starter

    SpringBoot1.x 启动配置原理 和 自定义starter 启动配置原理 本节源码 启动过程主要为: new SpringApplication(sources) 创建 SpringAppli ...

  3. springboot启动配置原理之二(运行run方法)

    public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); s ...

  4. springboot 启动配置原理【转】【补】

    创建应用 几个重要的事件回调机制  , 配置在META-INF/spring.factories ApplicationContextInitializer SpringApplicationRunL ...

  5. SpringBoot之自动配置原理

    我在前面的Helloworld的程序中已经分析过一次,配置原理了: 1).SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration 2).@En ...

  6. 面试题: SpringBoot 的自动配置原理

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 3.Spring Boot 的自动配置原理 package com.mmall; import org. ...

  7. SpringBoot的自动配置原理

    一.入口 上篇注解@SpringBootApplication简单分析,说到了@SpringBootApplication注解的内部结构, 其中@EnableAutoConfiguration利用En ...

  8. SpringBoot的自动配置原理过程解析

    SpringBoot的最大好处就是实现了大部分的自动配置,使得开发者可以更多的关注于业务开发,避免繁琐的业务开发,但是SpringBoot如此好用的 自动注解过程着实让人忍不住的去了解一番,因为本文的 ...

  9. 七、Spring Boot 启动配置原理

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

随机推荐

  1. Flutter移动电商实战 --(19)首页_火爆专区商品接口制作

    Dart中可选参数的设置 上节课在作通用方法的时候,我们的参数使用了一个必选参数,其实我们可以使用一个可选参数.Dart中的可选参数,直接使用“{}”(大括号)就可以了.可选参数在调用的时候必须使用p ...

  2. Sublime Text 编译运行Kotlin

    Sublime Text 编译运行Kotlin 转 https://blog.csdn.net/pirate7777777/article/details/72655293 kotlin最近是火了,所 ...

  3. 阶段5 3.微服务项目【学成在线】_day03 CMS页面管理开发_13-删除页面-前端-Api调用

    增加删除链接 <el-button size="small" type="text" @click="del(page.row.pageId)& ...

  4. [转]c3p0学习-JdbcUtil工具类

    原文:https://www.cnblogs.com/jonny-xu/p/6374163.html 一.需要jar包: c3p0-0.9.1.2.jar mysql-connector-java-5 ...

  5. windows10下idea快捷键文件

    没详细测试. https://my.oschina.net/superwen/blog/833482 |快捷键|英文说明|说明|冲突 |---|---|--| |Ctrl + Shift + F||根 ...

  6. java中序列化的作用

    一  什么叫序列化 通俗点讲:它是处理对象流的一种机制,即可以很方便的保存内存中java对象的状态,同时也为了方便传输. 二 序列化有什么作用 1.方便传输,速度快,还很安全,被调用方序列化,调用方反 ...

  7. mysql常用引擎

    经常用MySQL数据库,但是,你在用的时候注意过没有,数据库的存储引擎,可能有注意但是并不清楚什么意思,可能根本没注意过这个问题,使用了默认的数据库引擎,当然我之前属于后者,后来成了前者,然后就有了这 ...

  8. 环境变量配置文件profile

    环境变量配置文件 在Ubuntu中有如下几个文件可以设置环境变量1./etc/profile:在登录时,操作系统定制用户环境时使用的第一个文件,此文件为系统的每个用户设置环境信息,当用户第一次登录时, ...

  9. 什么是Java内部类?

    如果大家想了解更多的知识和技术,大家可以 搜索我的公众号:理想二旬不止 (尾部有二维码)或者访问我的 个人技术博客 www.ideal-20.cn 这样阅读起来会更加舒适一些 非常高兴与大家交流,学习 ...

  10. Oracle的查询-分页查询

    --Oracle中的分页 --rownum行号:当我们做select操作时候 --每查询出一行记录,就在该行加上一个行号 --行号从1开始,一次递增,不能跳着走 ----emp表工资倒叙排列后,每页5 ...