此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.6spring-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表达式、forloop 或任何其他 Kotlin 结构。这可能很有用 当您需要根据动态数据(例如,从数据库)注册路由时。

有关具体示例,请参阅 MiXiT 项目spring-doc.cadn.net.cn

MockMvc 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 多平台序列化

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

要启用它,请按照这些说明添加相关的依赖项 和 plugin。使用 Spring MVC 和 WebFlux 时,如果 Kotlin 序列化位于 Classpath 中,则默认配置 Kotlin 序列化,并且 其他变体(如 Jackson)则不是。如果需要,请手动配置转换器或编解码器。spring-doc.cadn.net.cn