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

同时引入Spring Boot Web与WebFlux时上下文路径不生效求助

问题:Spring Boot同时引入Web和WebFlux依赖时上下文路径不生效

环境与配置

引入的依赖

implementation "org.springframework.boot:spring-boot-starter-web:2.7.15"
implementation "org.springframework.boot:spring-boot-starter-webflux:2.7.15"

控制器代码

@RequestMapping(value = "/", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> index() {
    Logs.Enter();
    return Flux.just("Controller up");
}

application.properties配置

# Spring boot port
server.port=8082
server.servlet.context-path=/custom

问题现象

启动应用后,自定义上下文路径未被识别,日志显示:

log: Starting Servlet engine: [Apache Tomcat/9.0.79]
[main] start: Tomcat started on port(s): 8082 (http) with context path ''

已尝试的解决方案

  • 参考相关方案调整配置
  • 设置Java系统属性指定上下文路径
  • 添加WebServerFactoryCustomizer Bean:
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
  webServerFactoryCustomizer() {
    return factory -> factory.setContextPath("/custom");
}
  • 补充配置项:
spring.webflux.base-path=/custom
server.servlet.contextPath=/custom

所有尝试均无效果,且官方文档未找到其他配置方法。但移除spring-boot-starter-web依赖后,Netty可正常识别spring.webflux.base-path=/custom,请求http://localhost:8082/custom可正常访问。

疑问

同时使用Web和WebFlux时,有没有办法解决上下文路径不生效的问题?


解决方案

当Spring Boot同时引入spring-boot-starter-web和spring-boot-starter-webflux时,框架会自动选择**Servlet栈(Tomcat)**作为Web容器,而非Reactor Netty。此时WebFlux的配置(如spring.webflux.base-path)不会生效,所有Web请求走Servlet栈逻辑,需针对Servlet栈做正确配置:

  1. 确保配置项格式正确
    Servlet栈的标准上下文路径配置为server.servlet.context-path=/custom(推荐横杠分隔的标准写法,避免驼峰写法的兼容问题)。

  2. 排查配置覆盖情况
    检查项目中是否有其他配置源(环境变量、命令行参数、application.yml、配置中心等)覆盖了该配置。可通过启动日志的Property Sources模块,查看配置加载顺序与最终生效值。

  3. 调整WebServerFactoryCustomizer实现
    若原Bean不生效,可直接绑定Tomcat容器的工厂类:

    @Bean
    public TomcatServletWebServerFactory tomcatFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.setContextPath("/custom");
        return factory;
    }
    
  4. 验证控制器访问路径
    控制器使用@RequestMapping("/"),上下文路径生效后,实际访问地址应为http://localhost:8082/custom/,需测试该路径是否能正常响应。

  5. 排查依赖冲突
    通过./gradlew dependencies(Gradle)或mvn dependency:tree(Maven)查看依赖树,排除第三方starter对Web容器配置的修改。

额外建议

大部分场景下无需同时引入Web和WebFlux依赖:

  • 若以响应式场景为主,移除spring-boot-starter-web,依赖Netty与WebFlux配置即可;
  • 若为Servlet场景,移除spring-boot-starter-webflux,简化配置逻辑。

内容的提问来源于stack exchange,提问作者rupweb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 00:22:20