Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register RouterFunction in @Bean method in Spring Boot 2.0.0.M2?

I'm playing around with Spring 5 features and I'm having some trouble registering RouterFunction, it will be read, but not mapped. (Tried by throwing 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 404, any clues on what I'm doing wrong? (I also tried without this @RequestMapping to /routes, it also returned 404 for /asd)

like image 354
Joonas Vali Avatar asked Jun 27 '17 07:06

Joonas Vali


2 Answers

No need add spring-boot-starter-web when you want to use Webflux, just add spring-boot-starter-webflux into project dependencies.

For your codes, remove @RequestMapping("/routes") if want to use pure RouterFunction. And your routingFunction bean does not specify which HTTP method will be used.

A working sample codes 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 the complete codes from: https://github.com/hantsy/spring-reactive-sample/tree/master/boot-routes

If you are stick on traditional @RestController and @RequestMapping, check another sample: https://github.com/hantsy/spring-reactive-sample/tree/master/boot

like image 39
Hantsy Avatar answered Sep 28 '22 19:09

Hantsy


I found the issue.

I had those dependencies both 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 the spring-boot-starter-web dependency and webflux started working properly.

Another solution was to keep the web dependency and exclude tomcat so 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>
like image 164
Joonas Vali Avatar answered Sep 28 '22 17:09

Joonas Vali