Spring Boot是如何确定ApplicationType的?

应用类型分类

Spring Boot通过依次遍历检查classpath下的Web类是否存在来确定的,这个也是Spring Boot的WebApplicationType推理逻辑。
Spring Boot将应用分为两类:

  1. Application(非Web应用)
  2. WebApplicationType(Web应用)

maven依赖确定应用类型

我们使用Spring Boot可以很快的启动一个Web应用,只需要有2个依赖,依赖决定了我们是什么应用类型:
spring boot parent依赖

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>3.0.0</version>
	<relativePath/> 
</parent>

如果你的工程是一个Servlet应用,那么就依赖spring boot web starter

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

如果你的工程是一个Reactive应用,那么就依赖spring boot webflux starter

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

如果你的工程不是一个Web应用,那么就依赖spring boot starter

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
</dependency>

应用类型推理源码及注释

实现代码如下:

// webApplicationType是SpringApplication类中的成员变量
this.webApplicationType = WebApplicationType.deduceFromClasspath();

// 推理WebApplicationType
static WebApplicationType deduceFromClasspath() {
	
	// 如果classpath中存在WebFlux并且classpath中不存在WebMvc才会使用Reactive
	// 那么如果在maven依赖中同时有spring-boot-starter-web和spring-boot-starter-webflux,那么WebApplicationType是SERVLET
	if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
			&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
		return WebApplicationType.REACTIVE;
	}
	
	// 如果classpath中既没有spring-boot-starter-web又没有spring-boot-starter-webflux
	// 那么启动的应用就不是Web应用
	for (String className : SERVLET_INDICATOR_CLASSES) {
		if (!ClassUtils.isPresent(className, null)) {
			return WebApplicationType.NONE;
		}
	}
	return WebApplicationType.SERVLET;
}
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐