【SpringBoot1】Spring Boot是如何推断你的工程类型的

2024-02-04 22:44

本文主要是介绍【SpringBoot1】Spring Boot是如何推断你的工程类型的,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我们的工程一般都是基于java的Servlet的,但是除此之外还有其他类型的,

在WebApplicationType里定义了常见的类型:

public enum WebApplicationType {/*** The application should not run as a web application and should not start an* embedded web server.*/NONE,/*** The application should run as a servlet-based web application and should start an* embedded servlet web server.*/SERVLET,/*** The application should run as a reactive web application and should start an* embedded reactive web server.*/REACTIVE;

从定义上也能看到,第一种是None类型,表示不是网络服务的类型,如果我们的服务不是web服务可以这么设置,但是这个应用场景极少。

第二种就是我们常用的SERVLRT方式,一般我们工程都要采用这种方式,即使不需要对外部用户提供服务,也需要与监控系统等交互,因此一般我们设置为Servet就行了。

第三种是REACTIVE,这个应该是支持响应式编程的,这个目前接触不多,暂且略过。

那么SpringBoot是如何判断我们的服务是哪种类型的呢?

一般我们SpringBoot的main入口都是这么写的:

@SpringBootApplication
@MapperScan("com.online_education.storage.mapper;")
public class TeacherServiceApp {public static void main(String[] args) {SpringApplication.run(TeacherServiceApp.class,args);}
}

其中@SpringBootApplication注解里其实是集成了三个:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(...)

这三个注解的功能我们后面分析,这里我们先回到main方法里的run()继续看:

SpringApplication.run(TeacherServiceApp.class,args);

此时内容是这样的:

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {return run(new Class<?>[] { primarySource }, args);}

这里的run没做什么,我们继续看run里的代码:

return new SpringApplication(primarySources).run(args);

这里主要是用反射创建我们的Main方法所在的对象,我们首先进入SpringApplication类里看一下,

	public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {this.resourceLoader = resourceLoader;Assert.notNull(primarySources, "PrimarySources must not be null");this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));this.webApplicationType = WebApplicationType.deduceFromClasspath();setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));this.mainApplicationClass = deduceMainApplicationClass();}

这里有一行很重要的代码:

this.webApplicationType = WebApplicationType.deduceFromClasspath();

这一行就是获取类型的,那具体如何获取的呢?我们继续看:

	static WebApplicationType deduceFromClasspath() {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;}

这里的isPresent()做什么的我们后面再细看,这里通过名字也能推测出来,大致是要判断是否存在的意思,第一个if部分就是判断是否为响应式REACTIVE类型,后面的for循环就是判断是否存在

SERVLET_INDICATOR_CLASSES里标记的类型,里面两个参数是web服务必须的,只要有一个不存在就会返回类型是空。

private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet","org.springframework.web.context.ConfigurableWebApplicationContext" };

可以看到,这里其实是两个写死的类的地址,因此这里其实主要到某个地方查是否加载了这两个类。

如果都存在,那就返回Servlet类型。

那具体到哪里查的呢?我们继续看ClassUtils.isPresent(className, null)的实现:

  public static boolean isPresent(String className, @Nullable ClassLoader classLoader) {try {forName(className, classLoader);return true;} catch (IllegalAccessError var3) {throw new IllegalStateException("Readability mismatch in inheritance hierarchy of class [" + className + "]: " + var3.getMessage(), var3);} catch (Throwable var4) {return false;}}

到这里,根据定义和forName这种写法,有经验的同学就知道了,这里是到JVM里查装载器是否载入了。

public static Class<?> forName(String name, @Nullable ClassLoader classLoader){
... 
Class elementClass;String elementName;if (name.endsWith("[]")) {elementName = name.substring(0, name.length() - "[]".length());elementClass = forName(elementName, classLoader);return Array.newInstance(elementClass, 0).getClass();} else if (name.startsWith("[L") && name.endsWith(";")) {elementName = name.substring("[L".length(), name.length() - 1);elementClass = forName(elementName, classLoader);return Array.newInstance(elementClass, 0).getClass();} else if (name.startsWith("[")) {elementName = name.substring("[".length());elementClass = forName(elementName, classLoader);return Array.newInstance(elementClass, 0).getClass();} else {ClassLoader clToUse = classLoader;if (classLoader == null) {clToUse = getDefaultClassLoader();}try {return Class.forName(name, false, clToUse);
... 
}

这里的写法就比较负责了,上面是一个递归,本质上是在读字节码文件,例如name.startsWith("[L") 这些都是读字节码用的。

 那字节码是保存在哪里的呢?学过JVM虚拟机原理的同学应该知道,字节码是保存在元空间的,所以这里SpringBoot在启动的时候是去元空间里查,看看我们有没有将Servlet的类信息加载进来。

到此我们就知道了,如果我们要启动web服务,需要先将Servlet加载进来,SpringBoot还会以此类型来判断是否启用web服务。

而且通过这个代码,我们也可以知道Servlet和响应式只能装载一个,如果两个都有,仍然会当做Servelt服务。

if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {return WebApplicationType.REACTIVE;}

很明显,如果我们启动SpringBoot的时候还没有将Servlet相关类加载进来,那自然启动就失败了。

这篇关于【SpringBoot1】Spring Boot是如何推断你的工程类型的的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/679015

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、