此版本仍在开发中,尚未被视为稳定版。如需最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

web

路由 DSL

Spring Framework 自带一个 Kotlin 路由 DSL,提供三种风格: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 是程序化的,意味着它允许通过 if 表达式、for 循环或任何其他 Kotlin 结构来实现 Bean 的自定义注册逻辑。当你需要根据动态数据(例如来自数据库的数据)来注册路由时,这会非常有用。

参见MiXiT 项目以获取一个具体示例。spring-doc.cadn.net.cn

MockMvc DSL

通过 MockMvc 的 Kotlin 扩展提供了 Kotlin DSL,以提供更符合 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

要启用它,请按照这些说明添加相关的依赖项和插件。在 Spring MVC 和 WebFlux 中,如果 Kotlin 序列化库位于类路径中且不存在其他变体(如 Jackson),则会默认进行配置。如有需要,可手动配置转换器或编解码器。spring-doc.cadn.net.cn