You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot响应式应用不遵循WebApplicationType设置的解决方法

解决Spring Boot 3.2.2中类路径含spring-boot-starter-web时强制启动Netty/Reactive WebFlux的问题

当类路径同时存在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 09:23:37