如何在Spring Boot 2.0.0.M2中的@Bean方法中注册RouterFunction?

Joo*_*ali 4 java spring spring-boot spring-webflux

我正在使用Spring 5的功能,我在注册时遇到了一些问题RouterFunction,它将被读取,但不会被映射.(通过在方法中抛出异常来尝试.)

@Configuration
@RequestMapping("/routes")
public class Routes {
  @Bean
  public RouterFunction<ServerResponse> routingFunction() {
    return RouterFunctions.route(RequestPredicates.path("/asd"), req -> ok().build());
  }
}
Run Code Online (Sandbox Code Playgroud)

/routes/asd在404中找到结果,任何关于我做错的线索?(我也试过没有这个@RequestMapping/routes,它也返回404 /asd)

Joo*_*ali 5

我发现了这个问题.

我在我的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>
Run Code Online (Sandbox Code Playgroud)

删除了spring-boot-starter-web依赖关系,webflux开始正常工作.

另一种解决方案是保持Web依赖性并排除tomcat,以便netty开始工作:

<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>
Run Code Online (Sandbox Code Playgroud)


Han*_*tsy 5

spring-boot-starter-web使用 Webflux 时无需添加,只需添加spring-boot-starter-webflux到项目依赖项中即可。

对于您的代码,@RequestMapping("/routes")如果要使用 pure ,请删除RouterFunction。并且您的routingFunctionbean 没有指定将使用哪种 HTTP 方法。

来自我的 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);
}
Run Code Online (Sandbox Code Playgroud)

检查完整代码:https : //github.com/hantsy/spring-reactive-sample/tree/master/boot-routes

如果您坚持使用传统@RestController@RequestMapping,请检查另一个示例:https : //github.com/hantsy/spring-reactive-sample/tree/master/boot