此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.6! |
Web
路由器 DSL
Spring Framework 附带了一个 Kotlin 路由器 DSL,有 3 种风格可供选择:
-
带路由器的 WebMvc.fn DSL { }
这些 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 loop 或任何其他 Kotlin 结构。这可能很有用
当您需要根据动态数据(例如,从数据库)注册路由时。 |
有关具体示例,请参阅 MiXiT 项目。
MockMvc 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 格式。
要启用它,请按照这些说明添加相关的依赖项 和 plugin。使用 Spring MVC 和 WebFlux 时,如果 Kotlin 序列化位于 Classpath 中,则默认配置 Kotlin 序列化,并且 其他变体(如 Jackson)则不是。如果需要,请手动配置转换器或编解码器。