在Spring Boot WebFlux上检索路径变量(功能方法)

时间:2018-07-30 02:29:55

标签: spring-boot kotlin spring-webflux

假设我有这个路由器定义:

@Component
class PersonRouter(private val handler: PersonHandler) {
  @Bean
  fun router(): RouterFunction<ServerResponse> = router {
    ("/api/people" and accept(MediaType.APPLICATION_JSON_UTF8)).nest {
      GET("/{id}") { handler.findById(it) }
    }
  }

然后是此处理程序:

@Component
@Transactional
class PersonHandler(private val repository: PersonRepository) {
  private companion object : KLogging()

  @Transactional(readOnly = true)
  fun findById(req: ServerRequest): Mono<ServerResponse> {
    logger.info { "${req.method()} ${req.path()}" }
    val uuid = ? // req.pathContainer().elements().last().value()
    return ServerResponse.ok()
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(BodyInserters.fromObject(repository.findById(uuid)))
        .switchIfEmpty(ServerResponse.notFound().build())
  }
}

如何从@PathVariable id: String访问标识符(在典型的@RestController上是ServerRequest),而不用正则表达式,字符串繁重的代码等进行黑魔法东西吗?

1 个答案:

答案 0 :(得分:3)

啊!找到了!

它是通过这样做的:req.pathVariable("id")

一直在……在官方Spring Framework(网络响应)文档中!