此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
Web
路由器 DSL
Spring Framework 附带一个 Kotlin 路由器 DSL,有 3 种版本可供选择:
这些 DSL 允许您编写干净且惯用的 Kotlin 代码来构建RouterFunction
实例,如以下示例所示:
@Configuration
class RouterRouterConfiguration {
@Bean
fun mainRouter(userHandler: UserHandler) = router {
accept(TEXT_HTML).nest {
GET("/") { ok().render("index") }
GET("/sse") { ok().render("sse") }
GET("/users", userHandler::findAllView)
}
"/api".nest {
accept(APPLICATION_JSON).nest {
GET("/users", userHandler::findAll)
}
accept(TEXT_EVENT_STREAM).nest {
GET("/users", userHandler::stream)
}
}
resources("/**", ClassPathResource("static/"))
}
}
此 DSL 是编程的,这意味着它允许自定义 bean 的注册逻辑
通过if 表达式,一个for 循环或任何其他 Kotlin 构造。这可能很有用
当您需要根据动态数据(例如,来自数据库)注册路由时。 |
有关具体示例,请参阅 MiXiT 项目。
模拟Mvc DSL
Kotlin DSL 通过MockMvc
Kotlin 扩展,以便提供更多
习惯的 Kotlin API 并允许更好的可发现性(不使用静态方法)。
val mockMvc: MockMvc = ...
mockMvc.get("/person/{name}", "Lee") {
secure = true
accept = APPLICATION_JSON
headers {
contentLanguage = Locale.FRANCE
}
principal = Principal { "foo" }
}.andExpect {
status { isOk }
content { contentType(APPLICATION_JSON) }
jsonPath("$.name") { value("Lee") }
content { json("""{"someBoolean": false}""", false) }
}.andDo {
print()
}
Kotlin 多平台序列化
Kotlin 多平台序列化是 在 Spring MVC、Spring WebFlux 和 Spring Messaging (RSocket) 中受支持。内置支持目前面向 CBOR、JSON、 和 ProtoBuf 格式。
要启用它,请按照这些说明添加相关依赖项 和插件。使用 Spring MVC 和 WebFlux,如果 Kotlin 序列化位于类路径中,则默认配置 Kotlin 序列化,并且 像Jackson这样的其他变体则不然。如果需要,请手动配置转换器或编解码器。