几个重要的事件回调机制:

1、配置在META-INF/spring.factories

ApplicationContextInitializer

SpringApplicationRunlistener

2、需要放在ioc容器中

3、ApplicationRunner

4、CommandLineRunner

一、创建SpringApplication对象

快速创建一个工程,在SpringBootApplication类中,main方法作为一个入口类,在在run()方法处打上断点,debug运行;

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {

//保存主配置类

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,然后保存起来

setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

//从类路径系找到META-INF/spring.factories配置的所有ApplicationListener

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

//从多个配置类中找到有main方法的主配置类

this.mainApplicationClass = deduceMainApplicationClass();

}

二、运行run方法

接着上一步的继续进行:

public ConfigurableApplicationContext run(String... args) {

StopWatch stopWatch = new StopWatch();

stopWatch.start();

ConfigurableApplicationContext context = null;

Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();

configureHeadlessProperty();

//获取SpringApplicationRunListeners ,从类路径下METTA-INF/spring.factories

SpringApplicationRunListeners listeners = getRunListeners(args);

//回调所有的SpringApplicationRunListeners.starting方法

listeners.starting();

try {

//封装命令行参数

ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);

//准备环境

ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);

//创建环境完成后回调SpringApplicationRunListeners.environmentPrepared();表示环境准备完成

configureIgnoreBeanInfo(environment);

Banner printedBanner = printBanner(environment);

//创建applicationContext,决定创建web的ioc还是普通的ioc

context = createApplicationContext();

exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,

new Class[] { ConfigurableApplicationContext.class }, context);

//准备上下文环境;将environment保存到ioc中;而且applyInitializers()

//applyInitializers():回调之前保存的所有的ApplicationContextInitializer的Initialize方法

//回调所有的SpringApplicationRunListeners.contextPrepared()

prepareContext(context, environment, listeners, applicationArguments, printedBanner);

//prepareContext运行完成以后回调所有的SpringApplicationRunListeners的contextLoaded()

//刷新容器;ioc容器初始化(如果是web应用还会创建嵌入式的tomcat);spring注解

//扫描,创建,加载所有组件的地方;(配置类,组件,自动配置)

refreshContext(context);

//从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调

//ApplicationRunner先回调,CommandLineRunner再回调

afterRefresh(context, applicationArguments);

stopWatch.stop();

if (this.logStartupInfo) {

new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);

}

listeners.started(context);

callRunners(context, applicationArguments);

}

catch (Throwable ex) {

handleRunFailure(context, ex, exceptionReporters, listeners);

throw new IllegalStateException(ex);

}

try {

listeners.running(context);

}

catch (Throwable ex) {

handleRunFailure(context, ex, exceptionReporters, null);

throw new IllegalStateException(ex);

}

//整个SpringBoot应用启动完成外汇返佣以后返回启动的ioc容器

return context;

}三、事件监听机制

依次将上面的几个监听机制进行创建,

HelloApplicationContextInitializer:

public class HelloApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

@Override

public void initialize(ConfigurableApplicationContext applicationContext) {

System.out.println("ApplicationContextInitializer...initialize..." + applicationContext);

}

}

HelloSpringApplicationRunListener:

public class HelloSpringApplicationRunListener implements SpringApplicationRunListener {

public HelloSpringApplicationRunListener(SpringApplication application, String[] args){

}

@Override

public void starting() {

System.out.println("SpringApplicationRunListener...starting...");

}

@Override

public void environmentPrepared(ConfigurableEnvironment environment) {

Object o = environment.getSystemProperties().get("os.name");

System.out.println("SpringApplicationRunListener...environment" +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");

}

}

HelloApplicationRunner:

@Component

public class HelloAppicationRunner implements ApplicationRunner {

@Override

public void run(ApplicationArguments args) throws Exception {

System.out.println("ApplicationRunner...run..");

}

}

HelloCommandLineRuinner:

@Component

public class HelloCommandLineRunner implements CommandLineRunner{

@Override

public void run(String... args) throws Exception {

System.out.println("CommandLineRunner...run..." + Arrays.asList());

}

}

前面提到的ApplicationContextInitializer和SpringApplicationRunlistener是需要进行配置的,配置的位置是在META-INF/spring.factories中,因此创建一个META-INF的文件夹,并创建spring.factories文件,

org.springframework.context.ApplicationContextInitializer=\

com.itlaoqi.springbootspringbootapplication.listener.HelloApplicationContextInitializer

org.springframework.context.SpringApplicationRunListener=\

com.itlaoqi.springbootspringbootapplication.listener.HelloSpringApplicationRunListener

配置完成后启动项目即可进行测试。

原文链接:https://blog.csdn.net/cyl101816/article/details/103582373

Spring Boot 2.x:SpringBoot的更多相关文章

  1. spring boot 系列之八:SpringBoot处理定时任务

    项目经常会用到定时任务,springboot自然是可以通过整合相关组件来实现的. 目前常用的定时任务的实现有两种: 通过spring 自带的定时器任务@Schedule来实现 通过Quartz来实现 ...

  2. spring boot 系列之七:SpringBoot整合Mybatis

    springboot已经很流行,但是它仍需要搭配一款ORM框架来实现数据的CRUD,之前已经分享过JdbcTemplete和JPA的整合,本次分享下Mybatis的整合. 对于mybatis的使用,需 ...

  3. Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控

    Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控 Spring Boot Actuator提供了对单个Spring Boot的监控,信息包含: ...

  4. Spring Boot入门(五):使用JDBC访问MySql数据库

    本系列博客记录自己学习Spring Boot的历程,如帮助到你,不胜荣幸,如有错误,欢迎指正! 在程序开发的过程中,操作数据库是必不可少的部分,前面几篇博客中,也一直未涉及到数据库的操作,本篇博客 就 ...

  5. Spring Boot入门(四):开发Web Api接口常用注解总结

    本系列博客记录自己学习Spring Boot的历程,如帮助到你,不胜荣幸,如有错误,欢迎指正! 在程序员的日常工作中,Web开发应该是占比很重的一部分,至少我工作以来,开发的系统基本都是Web端访问的 ...

  6. Spring Boot入门(二):使用Profile实现多环境配置管理&如何获取配置文件值

    在上一篇博客Spring Boot入门(一):使用IDEA创建Spring Boot项目并使用yaml配置文件中,我们新建了一个最原始的Spring Boot项目,并使用了更为流行的yaml配置文件. ...

  7. Spring Boot入门(一):使用IDEA创建Spring Boot项目并使用yaml配置文件

    由于公司最近在做技术转型(从.Net转Java),因此自己也开启了学习Java之路.学习Java怎么能不学习这几年这么火的Spring Boot框架,由于自己有总结的习惯,因此会把学习的过程以博客的形 ...

  8. (转)Spring Boot 2 (八):Spring Boot 集成 Memcached

    http://www.ityouknow.com/springboot/2018/09/01/spring-boot-memcached.html Memcached 介绍 Memcached 是一个 ...

  9. (转)Spring Boot(二十):使用 spring-boot-admin 对 Spring Boot 服务进行监控

    http://www.ityouknow.com/springboot/2018/02/11/spring-boot-admin.html 上一篇文章<Spring Boot(十九):使用 Sp ...

随机推荐

  1. 攻防世界 | CGfsb

    所以题目要求是输入生日1926l

  2. (转)Kubernetes 配置Pod和容器(十七) 使用Secrets管理安全证书

    转:https://www.jianshu.com/p/530b3642c642 本章节展示了如何把密码秘钥等敏感数据安全的注入到Pod里面. 转换安全数据成base-64表示 假设你有两个秘密数据: ...

  3. POJ 1066 Treasure Hunt [想法题]

    题目链接: http://poj.org/problem?id=1066 --------------------------------------------------------------- ...

  4. 《图解设计模式》读书笔记2-1 Template Method模式

    目录 模板方法模式 类图 思想: 模板方法模式 在父类中定义流程,在子类中实现具体的方法. 类图 代码 //抽象类 public abstract class AbstractDisplay { pu ...

  5. 测开之路七十九:python 文件处理和对象的写入读取

    """处理文件:open(文件名, 模式,编码) 'r' 打开阅读(默认)'w' 打开写入,首先截断文件'x' 打开独占创建,如果文件已经存在则失败'a' 打开写入,追加 ...

  6. java数组,遍历数组

    数组:一组具有相同数据类型的集合(容器) 1.数组声明格式: 数据类型 [] 数组名 = new 数据类型[长度]: 数组长度一旦确定无法更改. 数组里的数据必须是相同类型或自动向上转型后兼容的类型 ...

  7. ECG 项目预研

    1. 数据的采集 智能安全帽,流数据,鉴于数据量大,应该是采集到云平台上,然后在云平台上对数据处理,是一种典型的物联网+大数据应用场景,考虑使用AWS或者阿里云,然后搭建Hadoop/Spark 环境 ...

  8. 编程语言-Python-GUI

    PyQt5 import sys from PyQt5 import QtWidgets,QtCore app = QtWidgets.QApplication(sys.argv) widget = ...

  9. php优化方法

    代码优化是开发程序和网站必不可少的一步,代码优化好了,可以大大增加程序的运行效率.使网站或程序加载反应更快.用户体验也就会更好.下面就为大家总结了50条PHP代码优化技巧. 1. 用单引号代替双引号来 ...

  10. ichunqiu在线挑战--网站综合渗透实验 writeup

    挑战链接:http://www.ichunqiu.com/tiaozhan/111 知识点:后台弱口令,md5破解,SQL Injection,写一句话木马,敏感信息泄露, 提权,登陆密码破解 这个挑 ...