Web

Router DSL

Spring Framework 提供了三种风格的 Kotlin 路由 DSL:

这些 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 MVC、Spring WebFlux 和 Spring Messaging (RSocket) 支持 Kotlin 多平台序列化。内置支持目前针对 CBOR、JSON 和 ProtoBuf 格式。

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

© . This site is unofficial and not affiliated with VMware.