
在 Spring Boot 3 中,server.servlet.context-path 仅对基于 Servlet 的 Web 应用(如 Spring MVC)有效;若项目依赖 spring-boot-starter-webflux(基于 Reactor Netty),该配置将被忽略,导致路径前缀失效。
在 spring boot 3 中,`server.servlet.context-path` 仅对基于 servlet 的 web 应用(如 spring mvc)有效;若项目依赖 `spring-boot-starter-webflux`(基于 reactor netty),该配置将被忽略,导致路径前缀失效。
Spring Boot 3 对 Web 编程模型做了明确区分:Spring MVC(阻塞式、Servlet 容器驱动)与 Spring WebFlux(响应式、非 Servlet 容器如 Netty 驱动)。而 server.servlet.context-path 是一个 Servlet 容器专属配置项,其底层依赖 ServletContext —— 这正是 WebFlux 默认嵌入式服务器(Netty)所不具备的抽象层。
因此,当你在 application.properties 中配置:
server.servlet.context-path=/api
但项目却引入了:
<dependency><groupid>org.springframework.boot</groupid><artifactid>spring-boot-starter-webflux</artifactid></dependency>
该配置将完全无效——因为 Netty 不实现 javax.servlet.ServletContext,Spring Boot 会静默忽略该属性,且不报错。此时所有接口仍暴露在根路径(如 http://localhost:8080/hello),而非预期的 http://localhost:8080/api/hello。
✅ 正确做法是:
- 若需使用
context-path(例如统一 API 网关路由、Nginx 前缀转发等场景),请切换为 Spring MVC 栈:
<!-- 移除 spring-boot-starter-webflux --> <!-- 添加以下依赖 --> <dependency><groupid>org.springframework.boot</groupid><artifactid>spring-boot-starter-web</artifactid></dependency>
启用后,Tomcat(默认 Servlet 容器)将正确解析并应用 context-path,所有 @RestController 接口自动挂载到 /api/** 下。
⚠️ 注意事项:
- 不要同时引入
spring-boot-starter-web和spring-boot-starter-webflux,二者存在自动配置冲突,可能导致启动失败或行为不可预测; - 若坚持使用 WebFlux 并需要路径前缀,应改用
spring.webflux.base-path=/api(适用于 WebFlux 的全局路径前缀,但语义不同于 Servlet context-path,不改变 DispatcherHandler 的根上下文); - Spring Boot 3+ 已移除对传统
web.xml和部分 Servlet 2.x 特性的支持,确保使用jakarta.servlet命名空间(Spring Boot 3 默认兼容)。
总结:server.servlet.context-path 是 Servlet 生态的契约,只在 spring-boot-starter-web + Servlet 容器(Tomcat/Jetty/Undertow)组合下生效。选型即契约——明确你的技术栈定位,是构建稳健 Spring Boot 3 应用的第一步。











