Spring Boot响应式应用不遵循WebApplicationType设置的解决方法
当类路径同时存在spring-boot-starter-web(Servlet栈)和spring-boot-starter-webflux(Reactive栈)时,即便你设置了web-application-type=REACTIVE或添加@EnableWebFlux,Spring Boot仍可能优先启动Tomcat——这是因为Servlet相关的自动配置类会被默认触发。以下是无需逐个排除spring-boot-starter-web的可行解决方案:
1. 禁用Servlet服务器核心自动配置类
直接在启动类上排除负责配置Tomcat等Servlet服务器的核心自动配置类,从根源阻止Tomcat启动:
@EnableConfigurationProperties @EnableWebFlux @SpringBootApplication(exclude = ServletWebServerFactoryAutoConfiguration.class) public class Application { public static void main(String[] args) { SpringApplication app = new SpringApplication(Application.class); app.setWebApplicationType(WebApplicationType.REACTIVE); app.run(args); } }
排除ServletWebServerFactoryAutoConfiguration后,Spring Boot会直接加载Reactive服务器(默认Netty)。
2. 通过配置文件排除自动配置
若不想修改代码,可在application.yml中添加自动配置排除规则:
spring: main: web-application-type: REACTIVE autoconfigure: exclude: org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
该配置会禁用Servlet服务器的自动配置逻辑,强制应用以Reactive模式启动。
3. 全局统一管控传递依赖(简化pom维护)
如果不想逐个模块排除spring-boot-starter-web,可在pom.xml的dependencyManagement中统一设置该依赖为provided,避免它被传递引入到类路径:
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>${spring-boot.version}</version> <scope>provided</scope> </dependency> </dependencies> </dependencyManagement>
设置为provided后,Maven会忽略所有依赖传递来的spring-boot-starter-web,同时不影响你显式引入的spring-boot-starter-webflux。
关键前提确认
确保你的pom.xml中已经引入了spring-boot-starter-webflux依赖,否则即便禁用了Servlet配置,也无法启动Netty:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
内容的提问来源于stack exchange,提问作者FerdTurgusen

