Spring boot源码深入学习(三) | SpringApplication实例化以及第一个监听器事件发布

回顾

上一篇 Spring boot源码深入学习(二) | 源码结构及启动流程概要
讲到springboot大体的启动流程:
【1】获取监听器
【2】准备环境
【3】控制台打印Banner
【4】创建容器,根据不同类型创建不同的容器
【5】实例化异常报告期实例,用于记录启动过程中的错误。
【6】准备容器,给刚刚创建的容器做一些初始化工作
【7】刷新容器,这一步至关重要。后续再做解析
【8】刷新容器后的一些操作,这里是空方法
下面详解分析一下。

SpringApplication的实例化

run方法调用过程中会实例化一个SpringApplication对象,里面操作了几步,这里详细介绍一下。
在这里插入图片描述
【1】设置启动环境:非web环境、web环境、reactive环境
【2】加载spring.factories文件,获取容器初始器ApplicationContextInitializer
【3】加载spring.factories文件,获取监听器
【4】从当前栈中获取当前执行main方法所在的class

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
		this.resourceLoader = resourceLoader;
		// 判断启动类是否为null
		Assert.notNull(primarySources, "PrimarySources must not be null");
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
		// 【1】设置启动环境:非web环境、web环境、reactive环境
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
		// 【2】启动过程第一次加载spring.factories文件,获取容器初始器ApplicationContextInitializer
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
		// 【3】加载spring.factories文件,获取监听器
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		// 【4】从当前栈中获取当前执行main方法所在的class
		this.mainApplicationClass = deduceMainApplicationClass();
	}

设置启动环境 WebApplicationType.deduceFromClasspath()
它是根据相关字节码文件是否存在来判断当前是何种环境

	// 判断项目启动环境,并设置
	static WebApplicationType deduceFromClasspath() {
		// DispatcherHandler字节码文件不存在,DispatcherServlet,ServletContainer字节码文件存在,则为REACTIVE环境
		if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null)
				&& !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
				&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
			return WebApplicationType.REACTIVE;
		}
		// class文件中不存在Servlet和ConfigurableWebApplicationContext,则设置环境为 NONE
		for (String className : SERVLET_INDICATOR_CLASSES) {
			if (!ClassUtils.isPresent(className, null)) {
				return WebApplicationType.NONE;
			}
		}
		// 设置环境为SERVLET
		return WebApplicationType.SERVLET;
	}

获取ApplicationContextInitializer和监听器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值