How to register RouterFunction in @Bean method in Spring Boot 2.0.0.M2?
I am playing with Spring 5 features and I have a registration problem RouterFunction
, it will be read but not displayed. (Tried by throwing an exception in the method.)
@Configuration
@RequestMapping("/routes")
public class Routes {
@Bean
public RouterFunction<ServerResponse> routingFunction() {
return RouterFunctions.route(RequestPredicates.path("/asd"), req -> ok().build());
}
}
Going to /routes/asd
results in a 404, any clues on what I am doing wrong? (I also tried without this @RequestMapping
before /routes
, it also returned 404 for /asd
)
source to share
I found the problem.
I had these dependencies as in my pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
removed spring-boot-starter-web dependency and webflux started working fine.
Another solution was keeping the dependencies online and throwing tomcat so that netty started working:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
source to share
No need to add spring-boot-starter-web
when you want to use Webflux, just add spring-boot-starter-webflux
depending on the project.
For your codes, remove @RequestMapping("/routes")
if you want to use clean RouterFunction
. And your routingFunction
bean doesn't specify which HTTP method will be used.
Working example code from my github:
@Bean
public RouterFunction<ServerResponse> routes(PostHandler postController) {
return route(GET("/posts"), postController::all)
.andRoute(POST("/posts"), postController::create)
.andRoute(GET("/posts/{id}"), postController::get)
.andRoute(PUT("/posts/{id}"), postController::update)
.andRoute(DELETE("/posts/{id}"), postController::delete);
}
Check codes: https://github.com/hantsy/spring-reactive-sample/tree/master/boot-routes
If you stick to traditional @RestController
and @RequestMapping
check another example: https://github.com/hantsy/spring-reactive-sample/tree/master/boot
source to share