SpringBoot启动过程

一、SpringBoot启动的时候,会构造一个SpringApplication的实例,构造SpringApplication的时候会进行初始化的工作,初始化的时候会做以下几件事:

1、把参数sources设置到SpringApplication属性中,这个sources可以是任何类型的参数.
2、判断是否是web程序,并设置到webEnvironment的boolean属性中.
3、创建并初始化ApplicationInitializer,设置到initializers属性中 。
4、创建并初始化ApplicationListener,设置到listeners属性中 。
5、初始化主类mainApplicatioClass。


二、SpringApplication构造完成之后调用run方法,启动SpringApplication,run方法执行的时候会做以下几件事:

1、构造一个StopWatch计时器,用来记录SpringBoot的启动时间 。
2、初始化监听器,获取SpringApplicationRunListeners并启动监听,用于监听run方法的执行。
3、创建并初始化ApplicationArguments,获取run方法传递的args参数。
4、创建并初始化ConfigurableEnvironment(环境配置)。封装main方法的参数,初始化参数,写入到 Environment中,发布 ApplicationEnvironmentPreparedEvent(环境事件),做一些绑定后返回Environment。
5、打印banner和版本。
6、构造Spring容器(ApplicationContext)上下文。先填充Environment环境和设置的参数,如果application有设置beanNameGenerator(bean)、resourceLoader(加载器)就将其注入到上下文中。调用初始化的切面,发布ApplicationContextInitializedEvent(上下文初始化)事件。
7、SpringApplicationRunListeners发布finish事件。
8、StopWatch计时器停止计时,日志打印总共启动的时间。
9、发布SpringBoot程序已启动事件(started())
10、调用ApplicationRunner和CommandLineRunner
11、最后发布就绪事件ApplicationReadyEvent,标志着SpringBoot可以处理就收的请求了(running())

SpringBoot启动过程

springboot的启动经过了一些一系列的处理,我们先看看整体过程的流程图
在这里插入图片描述
你别说,步骤还挺多,但是不要紧,为了帮助大家理解,接下来将上面的编号一个个地讲解,以通俗易懂的方式告诉大家,里面都做了什么事情,废话不多说,开整

1、运行 SpringApplication.run() 方法

可以肯定的是,所有的标准的springboot的应用程序都是从run方法开始的

package com.spring;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
 
@SpringBootApplication
public class App  {
 
    public static void main(String[] args) {
        // 启动springboot
        ConfigurableApplicationContext run = SpringApplication.run(App.class, args);
    }
 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

进入run方法后,会 new 一个SpringApplication 对象,创建这个对象的构造函数做了一些准备工作,编号第2~5步就是构造函数里面所做的事情

	/**
	 * Static helper that can be used to run a {@link SpringApplication} from the
	 * specified sources using default settings and user supplied arguments.
	 * @param primarySources the primary sources to load
	 * @param args the application arguments (usually passed from a Java main method)
	 * @return the running {@link ApplicationContext}
	 */
	public static ConfigurableApplicationContext run(Class<?>[] primarySources,
			String[] args) {
		return new SpringApplication(primarySources).run(args);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

另外在说明一下,springboot启动有三种方式,其他的启动方式可参照我的另一个帖子: SpringBoot的三种启动方式

2、确定应用程序类型

在SpringApplication的构造方法内,首先会通过 WebApplicationType.deduceFromClasspath(); 方法判断当前应用程序的容器,默认使用的是Servlet 容器,除了servlet之外,还有NONE 和 REACTIVE (响应式编程);
在这里插入图片描述

3、加载所有的初始化器

这里加载的初始化器是springboot自带初始化器,从从 META-INF/spring.factories 配置文件中加载的,那么这个文件在哪呢?自带有2个,分别在源码的jar包的 spring-boot-autoconfigure 项目 和 spring-boot 项目里面各有一个
在这里插入图片描述
spring.factories文件里面,看到开头是 org.springframework.context.ApplicationContextInitializer 接口就是初始化器了 ,
在这里插入图片描述
当然,我们也可以自己实现一个自定义的初始化器:实现 ApplicationContextInitializer接口既可

MyApplicationContextInitializer.java

package com.spring.application;
 
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
/**
 * 自定义的初始化器
 */
public class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        System.out.println("我是初始化的 MyApplicationContextInitializer...");
    }
}

在resources目录下添加 META-INF/spring.factories 配置文件,内容如下,将自定义的初始化器注册进去;

org.springframework.context.ApplicationContextInitializer=\
com.spring.application.MyApplicationContextInitializer
  • 1
  • 2

在这里插入图片描述
启动springboot后,就可以看到控制台打印的内容了,在这里我们可以很直观的看到它的执行顺序,是在打印banner的后面执行的;
在这里插入图片描述

4、加载所有的监听器

加载监听器也是从 META-INF/spring.factories 配置文件中加载的,与初始化不同的是,监听器加载的是实现了 ApplicationListener 接口的类
在这里插入图片描述
自定义监听器也跟初始化器一样,依葫芦画瓢就可以了,这里不在举例;

5、设置程序运行的主类

deduceMainApplicationClass(); 这个方法仅仅是找到main方法所在的类,为后面的扫包作准备,deduce是推断的意思,所以准确地说,这个方法作用是推断出主方法所在的类;
在这里插入图片描述

6、开启计时器

程序运行到这里,就已经进入了run方法的主体了,第一步调用的run方法是静态方法,那个时候还没实例化SpringApplication对象,现在调用的run方法是非静态的,是需要实例化后才可以调用的,进来后首先会开启计时器,这个计时器有什么作用呢?顾名思义就使用来计时的嘛,计算springboot启动花了多长时间;关键代码如下:

// 实例化计时器
StopWatch stopWatch = new StopWatch(); 
// 开始计时
stopWatch.start();
  • 1
  • 2
  • 3
  • 4

run方法代码段截图
在这里插入图片描述

7、将java.awt.headless设置为true

这里将java.awt.headless设置为true,表示运行在服务器端,在没有显示器器和鼠标键盘的模式下照样可以工作,模拟输入输出设备功能。

做了这样的操作后,SpringBoot想干什么呢?其实是想设置该应用程序,即使没有检测到显示器,也允许其启动.对于服务器来说,是不需要显示器的,所以要这样设置.

方法主体如下:

	private void configureHeadlessProperty() {
		System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty(
				SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
	}
  • 1
  • 2
  • 3
  • 4

通过方法可以看到,setProperty()方法里面又有个getProperty();这不多此一举吗?其实getProperty()方法里面有2个参数, 第一个key值,第二个是默认值,意思是通过key值查找属性值,如果属性值为空,则返回默认值 true;保证了一定有值的情况;

8、获取并启用监听器

这一步 通过监听器来实现初始化的的基本操作,这一步做了2件事情

  1. 创建所有 Spring 运行监听器并发布应用启动事件
  2. 启用监听器
    在这里插入图片描述

9、设置应用程序参数

将执行run方法时传入的参数封装成一个对象
在这里插入图片描述
仅仅是将参数封装成对象,没啥好说的,对象的构造函数如下

	public DefaultApplicationArguments(String[] args) {
		Assert.notNull(args, "Args must not be null");
		this.source = new Source(args);
		this.args = args;
	}
  • 1
  • 2
  • 3
  • 4
  • 5

那么问题来了,这个参数是从哪来的呢?其实就是main方法里面执行静态run方法传入的参数,
在这里插入图片描述

10、准备环境变量

准备环境变量,包含系统属性和用户配置的属性,执行的代码块在 prepareEnvironment 方法内在这里插入图片描述
打了断点之后可以看到,它将maven和系统的环境变量都加载进来了
在这里插入图片描述

11、忽略bean信息

这个方法configureIgnoreBeanInfo() 这个方法是将 spring.beaninfo.ignore 的默认值值设为true,意思是跳过beanInfo的搜索,其设置默认值的原理和第7步一样;

    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());
		}
	}

当然也可以在配置文件中添加以下配置来设为false

spring.beaninfo.ignore=false
  • 1

目前还不知道这个配置的具体作用,待作者查明后在补上

12、打印 banner 信息

显而易见,这个流程就是用来打印控制台那个很大的spring的banner的,就是下面这个东东
在这里插入图片描述
那他在哪里打印的呢?他在 SpringBootBanner.java 里面打印的,这个类实现了Banner 接口,

而且banner信息是直接在代码里面写死的;
在这里插入图片描述
有些公司喜欢自定义banner信息,如果想要改成自己喜欢的图标该怎么办呢,其实很简单,只需要在resources目录下添加一个 banner.txt 的文件即可,txt文件内容如下

                 _           _
                (_)         | |
 _   _  _____  ___ _ __   __| | ___  _ __   __ _
| | | |/ _ \ \/ / | '_ \ / _` |/ _ \| '_ \ / _` |
| |_| |  __/>  <| | | | | (_| | (_) | | | | (_| |
 \__, |\___/_/\_\_|_| |_|\__,_|\___/|_| |_|\__, |
  __/ |                                     __/ |
 |___/                                     |___/
:: yexindong::

一定要添加到resources目录下,别加错了
在这里插入图片描述
只需要加一个文件即可,其他什么都不用做,然后直接启动springboot,就可以看到效果了
在这里插入图片描述

13、创建应用程序的上下文

实例化应用程序的上下文, 调用 createApplicationContext() 方法,这里就是用反射创建对象,没什么好说的;
在这里插入图片描述

14、实例化异常报告器

异常报告器是用来捕捉全局异常使用的,当springboot应用程序在发生异常时,异常报告器会将其捕捉并做相应处理,在spring.factories 文件里配置了默认的异常报告器,

在这里插入图片描述
需要注意的是,这个异常报告器只会捕获启动过程抛出的异常,如果是在启动完成后,在用户请求时报错,异常报告器不会捕获请求中出现的异常,
在这里插入图片描述
了解原理了,接下来我们自己配置一个异常报告器来玩玩;

MyExceptionReporter.java 继承 SpringBootExceptionReporter 接口

package com.spring.application;
 
import org.springframework.boot.SpringBootExceptionReporter;
import org.springframework.context.ConfigurableApplicationContext;
 
public class MyExceptionReporter implements SpringBootExceptionReporter {
 
 
    private ConfigurableApplicationContext context;
    // 必须要有一个有参的构造函数,否则启动会报错
    MyExceptionReporter(ConfigurableApplicationContext context) {
        this.context = context;
    }
 
    @Override
    public boolean reportException(Throwable failure) {
        System.out.println("进入异常报告器");
        failure.printStackTrace();
        // 返回false会打印详细springboot错误信息,返回true则只打印异常信息 
        return false;
    }
}

在 spring.factories 文件中注册异常报告器

# Error Reporters 异常报告器
org.springframework.boot.SpringBootExceptionReporter=\
com.spring.application.MyExceptionReporter

在这里插入图片描述
接着我们在application.yml 中 把端口号设置为一个很大的值,这样肯定会报错,

server:
  port: 80828888

启动后,控制台打印如下图
在这里插入图片描述

15、准备上下文环境

这里准备的上下文环境是为了下一步刷新做准备的,里面还做了一些额外的事情;
在这里插入图片描述

15.1、实例化单例的beanName生成器

在 postProcessApplicationContext(context); 方法里面。使用单例模式创建 了BeanNameGenerator 对象,其实就是beanName生成器,用来生成bean对象的名称

15.2、执行初始化方法

初始化方法有哪些呢?还记得第3步里面加载的初始化器嘛?其实是执行第3步加载出来的所有初始化器,实现了ApplicationContextInitializer 接口的类

15.3、将启动参数注册到容器中

这里将启动参数以单例的模式注册到容器中,是为了以后方便拿来使用,参数的beanName 为 :springApplicationArguments

16、刷新上下文

刷新上下文已经是spring的范畴了,自动装配和启动 tomcat就是在这个方法里面完成的,还有其他的spring自带的机制在这里就不一一细说了,
在这里插入图片描述

17、刷新上下文后置处理

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) {
	}

18、结束计时器

到这一步,springboot其实就已经完成了,计时器会打印启动springboot的时长
在这里插入图片描述
在控制台看到启动还是挺快的,不到2秒就启动完成了;
在这里插入图片描述

19、发布上下文准备就绪事件

告诉应用程序,我已经准备好了,可以开始工作了
在这里插入图片描述

20、执行自定义的run方法

这是一个扩展功能,callRunners(context, applicationArguments) 可以在启动完成后执行自定义的run方法;有2中方式可以实现:

  1. 实现 ApplicationRunner 接口
  2. 实现 CommandLineRunner 接口

接下来我们验证一把,为了方便代码可读性,我把这2种方式都放在同一个类里面

package com.spring.init;
 
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
 
/**
 * 自定义run方法的2种方式
 */
@Component
public class MyRunner implements ApplicationRunner, CommandLineRunner {
 
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(" 我是自定义的run方法1,实现 ApplicationRunner 接口既可运行"        );
    }
 
    @Override
    public void run(String... args) throws Exception {
        System.out.println(" 我是自定义的run方法2,实现 CommandLineRunner 接口既可运行"        );
    }
}

启动springboot后就可以看到控制台打印的信息了
在这里插入图片描述

  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pjh_666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值