路由器 DSL

Spring Framework 附带了 Kotlin 路由器 DSL,提供 3 种版本:Spring中文文档

这些 DSL 允许您编写干净且惯用的 Kotlin 代码来构建实例,如以下示例所示:RouterFunctionSpring中文文档

@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 的自定义注册逻辑 通过表达式、循环或任何其他 Kotlin 构造。这可能很有用 当您需要根据动态数据(例如,从数据库)注册路由时。iffor

有关具体示例,请参阅 MiXiT 项目Spring中文文档

此 DSL 是编程的,这意味着它允许 Bean 的自定义注册逻辑 通过表达式、循环或任何其他 Kotlin 构造。这可能很有用 当您需要根据动态数据(例如,从数据库)注册路由时。iffor

MockMvc DSL的

Kotlin DSL 通过 Kotlin 扩展提供,以提供更多 惯用的 Kotlin API,并允许更好的可发现性(不使用静态方法)。MockMvcSpring中文文档

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中文文档

通过利用依赖关系,它 可以使用此类功能来呈现基于 Kotlin 的模板kotlinx.html并插入 DSL 或 Kotlin 多行。scripting-jsr223StringSpring中文文档

build.gradle.ktsSpring中文文档

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

配置通常用 和 bean 完成。ScriptTemplateConfigurerScriptTemplateViewResolverSpring中文文档

KotlinScriptConfiguration.ktSpring中文文档

@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中文文档

Kotlin 多平台序列化

Kotlin 多平台序列化是 在 Spring MVC、Spring WebFlux 和 Spring Messaging (RSocket) 中受支持。内置支持目前面向 CBOR、JSON 和 ProtoBuf 格式。Spring中文文档

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