问题发现
创捷了spring-web项目,然后在学习spring-webflux的时候代码编写后请求解决报404,示例代码如下:
@component public class myhandler { public mono<serverresponse> handlerequest(serverrequest request) { // 处理请求逻辑 string name = request.queryparam("name").orelse("anonymous"); string message = "hello, " + name + "!"; // 构建响应 return serverresponse.ok().body(bodyinserters.fromvalue(message)); } } @configuration @enablewebflux public class mywebfluxconfig { @bean public routerfunction<serverresponse> route(myhandler handler) { return routerfunctions.route() .get("/hello", handler::handlerequest) .build(); } }
pom依赖文件
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-webflux</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency>
启动成功后,请求如图
然后进行一系列的问题排查
问题解决
spring mvc 和 spring webflux 是两个不同的框架,用于构建 web 应用程序。由于这两个框架之间的差异,建议一个项目只用一个框架。
请求404,先baidu,发现对这个问题解决方案特别少,然后看网上别人的案例发现都有@enablewebflux
注解,加上后启动一堆错误来了。
一切的来源都是spring mvc 和spring webflux一起使用导致的,所以还是重新建一个项目再学习把。
问题一:the bean ‘requestmappinghandlermapping’, defined in class path resource [org/springframework/web/reactive/config/delegatingwebfluxconfiguration.class],
完整错误日志内容:
the bean ‘requestmappinghandlermapping’, defined in class path resource [org/springframework/web/reactive/config/delegatingwebfluxconfiguration.class], could not be registered. a bean with that name has already been defined in class path resource [org/springframework/web/servlet/config/annotation/delegatingwebmvcconfiguration.class] and overriding is disabled.
这个问题就是说requestmappinghandlermapping的bean重复了,但是全局搜索找不到这个bean,应该是默认自带的。
再application.properties
或application.yml
文件中加入配置:
spring.main.allow-bean-definition-overriding=true
当您的应用程序启动时,现有的bean定义将被新的定义所覆盖。
问题二:the java/xml config for spring mvc and spring webflux cannot both be enabled, e.g. via @enablewebmvc and @enablewebflux, in the same application.
看网上案例都有加@enablewebflux
注解,以为是没加注解导致访问404,加上后报错:
caused by: java.lang.illegalstateexception: the java/xml config for spring mvc and spring webflux cannot both be enabled, e.g. via @enablewebmvc and @enablewebflux, in the same application.
找到@enablewebmvc
注解,删除后,重启即可(其实不加注解也是可以请求的)。
问题三:请求404
将上面的问题都解决后,请求发现还是报404,然后就是再pom依赖文件中,删除spring-web依赖,重新编译后重启,发现依旧不行,最后发现springboot可以知道应用程序的web应用程序类型:
在配置文件(如application.properties
或application.yml
)中,添加以下属性:
spring.main.web-application-type = reactive
它有两个可选值:
servlet:表示将应用程序配置为使用传统的servlet api和阻塞i/o操作的web堆栈。这是默认值,适用于大多数传统的spring mvc应用程序。
reactive:表示将应用程序配置为使用reactive编程模型和非阻塞i/o操作的web堆栈。这适用于使用spring webflux构建的响应式应用程序。
最后请求接口,如图:
问题解决。
总结
到此这篇关于spring-web与spring-webflux冲突问题解决的文章就介绍到这了,更多相关spring-web与spring-webflux冲突内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论