Spring Boot是如何确定ApplicationType的

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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值