在 Spring Boot WebFlux 上检索路径变量(函数式方法)
Retrieve path variable on Spring Boot WebFlux (functional approach)
假设我有这个路由器定义:
@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())
}
}
如何从 ServerRequest
访问标识符(典型的 @RestController
上的 @PathVariable id: String
)而不使用正则表达式、字符串重载提升、还有这样的事情?
啊!找到了!
通过做:req.pathVariable("id")
它一直在那里...在官方 Spring Framework(Web Reactive)文档中!
假设我有这个路由器定义:
@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())
}
}
如何从 ServerRequest
访问标识符(典型的 @RestController
上的 @PathVariable id: String
)而不使用正则表达式、字符串重载提升、还有这样的事情?
啊!找到了!
通过做:req.pathVariable("id")
它一直在那里...在官方 Spring Framework(Web Reactive)文档中!