假设我有这个路由器定义:
@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
),而不用正则表达式,字符串繁重的代码等进行黑魔法东西吗?