|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
Web
路由器DSL
Spring Framework 随附一个 Kotlin 路由 DSL,有 3 种不同的风格:
-
WebMvc.fn DSL 与 router { }
-
WebFlux.fn 响应式 DSL 与 router { }
-
WebFlux.fn [协程] DSL 与 coRouter { }
这些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是编程式的,这意味着它允许通过if表达式、for循环或任何其他Kotlin结构来注册自定义的bean逻辑。当需要根据动态数据(例如,来自数据库的数据)注册路由时,这可能会很有用。 |
查看 MiXiT 项目 以获取具体示例。
MockMvc DSL
通过 MockMvc 个 Kotlin 扩展提供了一个 Kotlin DSL,以提供更符合 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 脚本模板
Spring Framework 提供了一个
ScriptTemplateView
,该功能支持 JSR-223 通过使用脚本引擎来渲染模板。
通过利用 scripting-jsr223 个依赖项,可以使用此功能来使用基于 Kotlin 的模板与
kotlinx.html DSL 或 Kotlin 多行插值 String 渲染。
build.gradle.kts
dependencies {
runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}
配置通常使用 ScriptTemplateConfigurer 和 ScriptTemplateViewResolver 个 bean 进行。
KotlinScriptConfiguration.kt
@Configuration
class KotlinScriptConfiguration {
@Bean
fun kotlinScriptConfigurer() = ScriptTemplateConfigurer().apply {
engineName = "kotlin"
setScripts("scripts/render.kts")
renderFunction = "render"
isSharedEngine = false
}
@Bean
fun kotlinScriptViewResolver() = ScriptTemplateViewResolver().apply {
setPrefix("templates/")
setSuffix(".kts")
}
}
查看 kotlin-script-templating 示例 项目以获取更多信息。
Kotlin 多平台序列化
从 Spring Framework 5.3 开始,Spring MVC、Spring WebFlux 和 Spring Messaging(RSocket)支持 Kotlin 多平台序列化。内置支持目前针对 CBOR、JSON 和 ProtoBuf 格式。
要启用它,请按照这些说明添加相关依赖项和插件。
使用 Spring MVC 和 WebFlux 时,如果 Kotlin 序列化和 Jackson 在类路径中,它们将默认配置。
Kotlin 序列化旨在仅序列化带有 @Serializable 注解的 Kotlin 类。
使用 Spring Messaging(RSocket)时,如果希望自动配置,请确保 Jackson、GSON 或 JSONB 不在类路径中,
如果需要 Jackson,请手动配置 KotlinSerializationJsonMessageConverter。