此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

Web

路由器 DSL

Spring Framework 附带一个 Kotlin 路由器 DSL,有 3 种版本可供选择:spring-doc.cadn.net.cn

这些 DSL 允许您编写干净且惯用的 Kotlin 代码来构建RouterFunction实例,如以下示例所示:spring-doc.cadn.net.cn

@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 项目spring-doc.cadn.net.cn

模拟Mvc DSL

Kotlin DSL 通过MockMvcKotlin 扩展,以便提供更多 习惯的 Kotlin API 并允许更好的可发现性(不使用静态方法)。spring-doc.cadn.net.cn

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 使用脚本引擎渲染模板。spring-doc.cadn.net.cn

通过利用scripting-jsr223依赖项, it 可以使用此类功能来渲染基于 Kotlin 的模板kotlinx.html DSL 或 Kotlin 多行插值String.spring-doc.cadn.net.cn

build.gradle.ktsspring-doc.cadn.net.cn

dependencies {
	runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}

配置通常使用ScriptTemplateConfigurerScriptTemplateViewResolver豆。spring-doc.cadn.net.cn

KotlinScriptConfiguration.ktspring-doc.cadn.net.cn

@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 示例 项目了解更多详情。spring-doc.cadn.net.cn

Kotlin 多平台序列化

Kotlin 多平台序列化是 在 Spring MVC、Spring WebFlux 和 Spring Messaging (RSocket) 中受支持。内置支持目前针对 CBOR、JSON 和 ProtoBuf 格式。spring-doc.cadn.net.cn

要启用它,请按照这些说明添加相关的依赖项和插件。 使用 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 位于类路径中,则默认配置它们,因为 Kotlin 序列化旨在仅序列化带有@Serializable. 使用 Spring Messaging (RSocket),如果您想要自动配置,请确保 Jackson、GSON 或 JSONB 都不在类路径中, 如果需要Jackson,则配置KotlinSerializationJsonMessageConverter手动下载。spring-doc.cadn.net.cn