dea*_*mon 2 spring spring-mvc kotlin spring-hateoas
Spring HATEOAS方法有一个 Kotlin 变体linkTo,它采用控制器的具体化类型参数和主体的函数:
org.springframework.hateoas.server.mvc WebMvcLinkBuilderDslKt.class public inline fun <reified C> linkTo(\n func: C.() \xe2\x86\x92 Unit\n): WebMvcLinkBuilder\nRun Code Online (Sandbox Code Playgroud)\n但我不知道如何实际使用它,因为我还没有找到任何有用的文档,而且 API 也不是很直观。我尝试过这样的:
\nlinkTo<MyHandler> { findById(req) }.toUriComponentsBuilder().build(mapOf("id" to 1)).toURL()\nRun Code Online (Sandbox Code Playgroud)\nreq我认为如果链接应该指向另一个方法,那么使用周围方法的对象是错误的。结果就是http://localhost:8080没有任何路径或参数。
如何与 Kotlin DSL 建立链接?
\n由于我使用的是 Spring WebMvc.fn:是否有另一种方法来构建与此框架的链接?
\n该函数func的参数linkTo是一个带有receiver的函数,其中receiver必须是Spring控制器。在函数内部,您应该调用控制器的方法之一。当 Spring HATEOAS 调用 时func,它作为接收者传递,而不是实际的控制器,而是代理。拦截代理上的方法调用,并根据方法调用(包括方法调用参数)创建链接。
给定一个控制器:
@RestController
class TestController {
@RequestMapping("/test/{path-var}")
@ResponseBody
fun test(@PathVariable("path-var") pathVar: String,
@RequestParam("param") param: Int) = Response()
}
Run Code Online (Sandbox Code Playgroud)
以下调用将产生http://localhost:8080/test/any?param=123
linkTo<TestController> { test("any", 123) }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1317 次 |
| 最近记录: |