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 是编程式的,这意味着它允许通过 |
请参阅 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
依赖项,
可以使用此功能通过
kotlinx.html DSL 或 Kotlin 多行插值 String
来渲染基于 Kotlin 的模板。
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 多平台序列化
Kotlin 多平台序列化 在 Spring MVC、Spring WebFlux 和 Spring Messaging (RSocket) 中得到支持。目前内置支持 CBOR、JSON 和 ProtoBuf 格式。
要启用它,请遵循 这些说明 来添加相关依赖项和插件。
对于 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 都在 classpath 中,它们将默认配置,因为
Kotlin 序列化旨在仅序列化用 @Serializable
注解的 Kotlin 类。
对于 Spring Messaging (RSocket),如果你希望自动配置,请确保 classpath 中没有 Jackson、GSON 或 JSONB;
如果需要 Jackson,请手动配置 KotlinSerializationJsonMessageConverter
。