Spring WebFlux访问/booking报NoHandlerFoundException,父Pom不可修改如何解决?
问题解决:WebFlux Router路由无法匹配的问题
问题根源
你的项目同时引入了Spring MVC(spring-boot-starter-web,来自不可修改的父pom)和Spring WebFlux(spring-boot-starter-webflux)。Spring Boot默认会优先选择Servlet栈(Tomcat)启动,而WebFlux的RouterFunction属于Reactive栈的路由定义,不会被Servlet容器识别,因此出现NoHandlerFoundException。
解决方案
方案1:强制指定Web应用类型为Reactive
在项目的配置文件(application.properties或application.yml)中添加以下配置,强制Spring Boot使用Reactive Web容器:
- 若使用
.properties文件:
spring.main.web-application-type=reactive
- 若使用
.yml文件:
spring: main: web-application-type: reactive
配置完成后,Spring Boot会启动Netty作为Reactive容器,WebFlux的路由配置会被正确加载,/booking接口即可正常访问。此方案无需修改pom,操作最简单,且不会影响父pom中其他依赖的正常使用。
方案2:在子pom中排除父pom传递的Spring MVC依赖
如果需要彻底移除Spring MVC依赖,可在子pom.xml中显式排除父pom传递的spring-boot-starter-web:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <!-- 排除父pom中传递的Spring MVC全量依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
此方式会完全移除spring-boot-starter-web及其所有依赖,项目将仅依赖WebFlux栈,Spring Boot会自动启动Reactive容器。
内容的提问来源于stack exchange,提问作者Rahul Raj
相关产品推荐
相关产品推荐

