SpringBoot启动流程分析之创建SpringApplication对象(一)

SpringBoot启动流程分析之创建SpringApplication对象(一)

目录:

文章目录

      • SpringBoot启动流程分析之创建SpringApplication对象(一)
          • 1、SpringApplication的构造方法
            • 1.1、推断应用程序类型
            • 1.2、设置Initializers
            • 1.3、设置Listener
            • 1.4、推断main方法所在类

流程分析

1、SpringApplication的构造方法

来看一下在SpringApplication对象的构造方法中都做了哪些事。

public SpringApplication(Class<?>... primarySources) {
	this(null, primarySources);
}
 
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
	this.resourceLoader = resourceLoader;
        //判断primarySources不能为空
	Assert.notNull(primarySources, "PrimarySources must not be null");
        //将primarySources放入SpringApplication的全局变量primarySources,Set集合中
	this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        //从类路径中推断应用程序类型放到SpringApplication的全局变量webApplicationType 
	this.webApplicationType = WebApplicationType.deduceFromClasspath();
        //从META-INF/spring.factories文件中获取ApplicationContextInitializer接口的实现类并利用反射创建对象返回放入SpringApplication的全局变量initializers,List集合中
	setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
        //同上,也是从META-INF/spring.factories文件中获取ApplicationListener接口的实现类并利用反射创建对象返回放入SpringApplication的全局变量listeners,List集合中
	setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        //通过获取当前调用栈,找到入口方法main所在的类,放入SpringApplication的全局变量mainApplicationClass 
	this.mainApplicationClass = deduceMainApplicationClass();
}
1.1、推断应用程序类型
private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
			"org.springframework.web.context.ConfigurableWebApplicationContext" };
 
private static final String WEBFLUX_INDICATOR_CLASS = "org."
			+ "springframework.web.reactive.DispatcherHandler";
 
private static final String WEBMVC_INDICATOR_CLASS = "org.springframework."
			+ "web.servlet.DispatcherServlet";
 
private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";
 
 
static WebApplicationType deduceFromClasspath() {
        //ClassUtils.isPresent()从默认classloader中判断是否存在对应的类型
	if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null)
			&& !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
			&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
		return WebApplicationType.REACTIVE;
	}
	for (String className : SERVLET_INDICATOR_CLASSES) {
		if (!ClassUtils.isPresent(className, null)) {
			return WebApplicationType.NONE;
		}
	}
	return WebApplicationType.SERVLET;
}

推断逻辑是:

先是判断默认的classloader中是否存在org.springframework.web.reactive.DispatcherHandler、且不存在org.springframework.web.servlet.DispatcherServlet、org.glassfish.jersey.servlet.ServletContainer,如果为true返回WebApplicationType.REACTIVE;

然后循环String数组,判断如果默认的classloader中是否不存在javax.servlet.Servlet和org.springframework.web.context.ConfigurableWebApplicationContext,如果不存在,则认为不是web应用程序,返回WebApplicationType.NONE;

最后是返回WebApplicationType.SERVLET。

三种返回类型的解释如下:

    1、WebApplicationType.NONE:不是web应用程序

    2、WebApplicationType.SERVLET:基于servlet的Web应用程序运行

    3、WebApplicationType.REACTIVE:响应式的web应用程序
1.2、设置Initializers

传入参数是class类型即ApplicationContextInitializer.class,最终调用方法是getSpringFactoriesInstances,注意第二个参数,传的是一个空的Class数组,则加载所有的配置的类,方便后续给定限定类型的时候无需再次加载,直接从cache中读取。

SpringFactoriesLoader.loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader):这个方法,其作用是使用给定的类加载器从“META-INF/spring.factories”加载给定类型的工厂实现的完全限定类名,即得到所有ApplicationContextInitializer接口实现类的完全限定类名,去重。

setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
 
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
		return getSpringFactoriesInstances(type, new Class<?>[] {});
	}
 
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
		Class<?>[] parameterTypes, Object... args) {
	ClassLoader classLoader = getClassLoader();
	// Use names and ensure unique to protect against duplicates
        //得到所有ApplicationContextInitializer接口的实现类
	Set<String> names = new LinkedHashSet<>(
			SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        //创建所有ApplicationContextInitializer接口实现类的实例
	List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
			classLoader, args, names);
        //根据order排序
	AnnotationAwareOrderComparator.sort(instances);
	return instances;
}

随后当做参数传递到createSpringFactoriesInstances方法中,这个方法主要作用就是根据传入的type类型,parameterTypes参数类型(空Class数组)以及得到的完全限定类名集合创建对象实例,其中getDeclaredConstructor方法作用是得到指定参数类型的构造方法,parameterTypes为空数组即的得到的就是默认构造方法。构造方法基本都是空的,所以无需关心创建Initializers实例的时候在构造方法中执行了什么操作。这些对象的initialize方法会在后面的run方法中被调用。

@SuppressWarnings("unchecked")
private <T> List<T> createSpringFactoriesInstances(Class<T> type,
		Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args,
		Set<String> names) {
        //new 一个跟检索出来的接口实现类相同size的List
	List<T> instances = new ArrayList<>(names.size());
	for (String name : names) {
		try {
                        //通过类加载器加载类
			Class<?> instanceClass = ClassUtils.forName(name, classLoader);
                        //判断是否为ApplicationContextInitializer接口的实现类
			Assert.isAssignable(type, instanceClass);
                        //得到指定参数类型的构造方法
			Constructor<?> constructor = instanceClass
					.getDeclaredConstructor(parameterTypes);
                        //创建对象
			T instance = (T) BeanUtils.instantiateClass(constructor, args);
                        //放到List中,返回
			instances.add(instance);
		}
		catch (Throwable ex) {
			throw new IllegalArgumentException(
					"Cannot instantiate " + type + " : " + name, ex);
		}
	}
	return instances;
}

spring.factories文件内容中Initializers如下。

在这里插入图片描述
在这里插入图片描述

1.3、设置Listener

这一步跟上面设置Initializers执行的操作是一样的。spring.factories文件内容中Listener如下。
在这里插入图片描述

整理一下Listener对应的Event

监听器事件类型
BackgroundPreinitializerApplicationStartingEvent、ApplicationEnvironmentPreparedEvent、ApplicationPreparedEvent、ApplicationStartedEvent、ApplicationReadyEvent、ApplicationFailedEvent、ApplicationContextInitializedEvent
ClearCachesApplicationListenerContextRefreshedEvent
ParentContextCloserApplicationListenerParentContextAvailableEvent
FileEncodingApplicationListenerApplicationEnvironmentPreparedEvent
AnsiOutputApplicationListenerApplicationEnvironmentPreparedEvent
ConfigFileApplicationListenerApplicationEnvironmentPreparedEvent、ApplicationPreparedEvent
DelegatingApplicationListenerApplicationEnvironmentPreparedEvent
ClasspathLoggingApplicationListenerApplicationEnvironmentPreparedEvent、ApplicationFailedEvent
LoggingApplicationListenerApplicationStartingEvent、ApplicationEnvironmentPreparedEvent、ApplicationPreparedEvent、ContextClosedEvent、ApplicationFailedEvent
LiquibaseServiceLocatorApplicationListenerApplicationStartingEvent
1.4、推断main方法所在类

StackTraceElement数组包含了StackTrace(堆栈轨迹)的内容,通过遍历它可以得到当前方法以及其定义类、调用行数等信息。
在这里插入图片描述

private Class<?> deduceMainApplicationClass() {
	try {
                //获取StackTraceElement数组,也就是这个栈的信息。
		StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
		for (StackTraceElement stackTraceElement : stackTrace) {
			if ("main".equals(stackTraceElement.getMethodName())) {
                                //stackTraceElement.getClassName(),得到定义类,即main方法所在类
				return Class.forName(stackTraceElement.getClassName());
			}
		}
	}
	catch (ClassNotFoundException ex) {
		// Swallow and continue
	}
	return null;
}

SpringApplication对象的创建过程就完成了。

Springboot 启动还可以使用流式API SpringApplicationBuilder的方式启动:

@SpringBootApplication
public class RegisterApplication {
	public static void main(String[] args) {
		new SpringApplicationBuilder(RegisterApplication.class)
				// 设置当前应用类型
				.web(WebApplicationType.SERVLET)
				// 设置 banner 横幅打印方式、有关闭、日志、控制台
				.bannerMode(Banner.Mode.OFF)
				// 设置自定义的 banner
				.banner()
				// 追加自定义的 initializer 到集合中 
				.initializers()
				// 追加自定义的 listeners 到集合中
				.listeners()
				.run(args);
	}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/605852.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Seata之XA 模式的使用

系列文章目录 文章目录 系列文章目录前言 前言 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站&#xff0c;这篇文章男女通用&#xff0c;看懂了就去分享给你的码吧。 Seata 是一款开源的…

计算机专业,求你别再玩了,我都替你们着急

明确学习目标和方向&#xff1a;确定自己希望在计算机领域的哪个方向深入发展&#xff0c;如前端开发、后端开发、数据库管理、人工智能等。根据目标方向&#xff0c;制定详细的学习计划&#xff0c;确保所学知识与未来职业方向相匹配。 【PDF学习资料文末获取】 扎实基础知识…

变配电工程 变配电室智能监控系统 门禁 视频 环境 机器人

一、方案背景 要真正了解无人值守配电房的运行模式&#xff0c;我们必须对“无人值守”这一概念有准确的理解。它并不意味着完全没有工作人员管理&#xff0c;而是通过技术设备和人机协作来确保配电房的正常运行。 利用变配电室智能监控系统&#xff0c;可以实时获得配电室各…

【优选算法】—Leetcode—11—— 盛最多水的容器

1.题目 11. 盛最多水的容器 给定一个长度为 n 的整数数组 height 。有 n 条垂线&#xff0c;第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线&#xff0c;使得它们与 x 轴共同构成的容器可以容纳最多的水。 返回容器可以储存的最大水量。 说明&#…

滑动窗口详解

目录 一、滑动窗口的特定步骤&#xff1a; 二、题目解析 1、⻓度最⼩的⼦数组---点击跳转题目 3、最⼤连续 1 的个数 III----点击跳转题目 4、将 x 减到 0 的最⼩操作数----点击跳转题目 5、⽔果成篮----点击跳转题目 滑动窗口是双指针算法中细分的一种&#xff0c;它由暴…

【AutoGPT】踩坑帖(follow李鱼皮)

本文写于2024年5月7日 参考视频&#xff1a;AutoGPT傻瓜式使用教程真实体验&#xff01; 对应文章&#xff1a;炸裂的AutoGPT&#xff0c;帮我做了个网站&#xff01; 平台&#xff1a;GitPod 云托管服务 原仓库已经改动很大&#xff0c;应使用的Repo为&#xff1a;Auto-GPT-ZH…

java后端15问!

前言 最近一位粉丝去面试一个中厂&#xff0c;Java后端。他说&#xff0c;好几道题答不上来&#xff0c;于是我帮忙整理了一波答案 G1收集器JVM内存划分对象进入老年代标志你在项目中用到的是哪种收集器&#xff0c;怎么调优的new对象的内存分布局部变量的内存分布Synchroniz…

中职大数据专业介绍:大数据技术应用

近年来&#xff0c;人工智能在经济发展、社会进步、国际政治经济格局等方面已经产生重大而深远的影响。规划纲要对“十四五”及未来十余年我国人工智能的发展目标、核心技术突破、智能化转型与应用&#xff0c;以及保障措施等多个方面都作出了部署。 据2020年全国教育事业发展统…

运用分支结构与循环结构写一个猜拳小游戏

下面我们运用平常所学的知识来写一个小游戏&#xff0c;这样能够加强我们学习的趣味性&#xff0c;并且能够更加的巩固我们所学的知识。 游戏代码&#xff1a; 直接放代码&#xff1a;&#xff08;手势可以使用数字来代替&#xff0c;比如0对应石头&#xff0c;1对应剪刀&…

Qexo:让你的静态博客动起来

Qexo是一个强大而美观的在线静态博客编辑器&#xff0c;它不仅限于编辑&#xff0c;而是将静态博客提升到新的高度。通过GPL3.0开源协议&#xff0c;Qexo提供了一个集编辑、管理、扩展于一体的平台&#xff0c;让静态博客也能拥有动态的元素。无论你是Hexo、Hugo还是Valaxy的用…

【论文阅读】<YOLOP: You Only Look Once for PanopticDriving Perception>

Abstract 全视驾驶感知系统是自动驾驶的重要组成部分。一个高精度的实时感知系统可以帮助车辆在驾驶时做出合理的决策。我们提出了一个全视驾驶感知网络&#xff08;您只需寻找一次全视驾驶感知网络&#xff08;YOLOP&#xff09;&#xff09;&#xff0c;以同时执行交通目标检…

C++类和对象中篇

&#x1f407; &#x1f525;博客主页&#xff1a; 云曦 &#x1f4cb;系列专栏&#xff1a;[C] &#x1f4a8;路漫漫其修远兮 吾将而求索 &#x1f49b; 感谢大家&#x1f44d;点赞 &#x1f60b;关注&#x1f4dd;评论 文章目录 &#x1f4d4;前言&#x1f4d4;1、类的六个…

源代码怎么加密防泄漏?9种方法教会你

想做源代码加密防止泄漏&#xff0c;首先要了解程序员可以通过哪些方式将源代码传输出去&#xff01; 程序员泄密的常见方式 物理方法&#xff1a; — 网线直连&#xff0c;即把网线从墙上插头拔下来&#xff0c;然后和一个非受控电脑直连; — winPE启动&#xff0c;通过光盘…

怎么写毕业论文的? 推荐4个AI工具

写作这件事一直让我们从小学时期就开始头痛&#xff0c;初高中时期800字的作文让我们焦头烂额&#xff0c;一篇作文里用尽了口水话&#xff0c;拼拼凑凑才勉强完成。 大学时期以为可以轻松顺利毕业&#xff0c;结果毕业前的最后一道坎拦住我们的是毕业论文&#xff0c;这玩意不…

常用目标检测算法介绍

目录 1. 常用目标检测算法 2. R-CNN 模型 3. Fast R-CNN 模型 4. Faster R-CNN 模型 5. SSD 模型 1. 常用目标检测算法 在深度学习框架下&#xff0c;目标检测方法通常涉及图像定位和分类两个关键方面。有两种主要的解决方法&#xff1a;一种是一阶&#xff08;one-stage&…

去除快捷方式的箭头图标

文章目录 取消箭头显示恢复箭头显示结果展示 添加快捷方式之后&#xff0c;会有箭头图标&#xff0c;部分场景下看着较为难受&#xff1a; 可以通过如下方式取消/显示箭头&#xff1a; 取消箭头显示 新建一个.bat文件&#xff0c;内部加入如下命令&#xff1a; reg add "…

2024北京市人工智能大模型行业应用分析报告

来源&#xff1a;北京市科学技术委员会 方向一为基于AIGC技术的智能审计合规研究&#xff0c;由北京银行提出&#xff0c;以 提高审计工作效率和准确性为核心目标&#xff0c;需要参赛企业针对检查内容&#xff0c; 利用大模型技术寻找并给出相关现象涉及的制度名称及相关原文…

element ui的确认提示框按钮样式修改

修改确认提示框的默认按钮样式&#xff0c;使用css强制修改 例&#xff1a; js代码&#xff1a; deleteUser(params){this.$confirm("您确定要删除吗&#xff1f;此操作无法撤销并且将永久删除所有数据。", "提示", { type: "warning", cancel…

新款锐科达SV-2402VP SIP广播音频模块18123651365支持RTP流音频广播

一、模块介绍 SV-2402VP网络音频模块是一款通用的独立SIP音频播放模块&#xff0c;其带2*15W功放音频输出&#xff0c;可以轻松地嵌入到OEM产品中。该模块对来自网络的SIP协议及RTP音频流进行解码播放。 该模块支持多种网络协议和音频解码协议&#xff0c;可用于VoIP和IP寻呼…

解决Tomcat日志乱码问题

1、 修改apache-tomcat-10.1.23/conf/server.xml URIEncoding"UTF-8"2、 修改apache-tomcat-10.1.23/conf/logging.properties # java.util.logging.ConsoleHandler.encoding UTF-8 java.util.logging.ConsoleHandler.encoding GBK参考 https://www.jb51.net/ar…
最新文章