Spring Boot通过依次遍历检查classpath下的Web类是否存在来确定的,这个也是Spring Boot的WebApplicationType推理逻辑。
Spring Boot将应用分为两类:
我们使用Spring Boot可以很快的启动一个Web应用,只需要有2个依赖,依赖决定了我们是什么应用类型:
spring boot parent依赖
org.springframework.boot spring-boot-starter-parent 3.0.0
如果你的工程是一个Servlet应用,那么就依赖spring boot web starter
org.springframework.boot spring-boot-starter-web
如果你的工程是一个Reactive应用,那么就依赖spring boot webflux starter
org.springframework.boot spring-boot-starter-webflux
如果你的工程不是一个Web应用,那么就依赖spring boot starter
org.springframework.boot spring-boot-starter
实现代码如下:
// 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是SERVLETif (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;
}