Web

Router DSL

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

Spring Framework comes with a Kotlin router DSL available in 3 flavors:

这些 DSL 让你编写简洁而符合 Kotlin 惯例的代码来构建 RouterFunction 实例,如下图所示:

These DSL let you write clean and idiomatic Kotlin code to build a RouterFunction instance as the following example shows:

@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 的注册逻辑。当您需要根据动态数据(例如,来自数据库)注册路由时,这可能会很有用。

This DSL is programmatic, meaning that it allows custom registration logic of beans through an if expression, a for loop, or any other Kotlin constructs. That can be useful when you need to register routes depending on dynamic data (for example, from a database).

请参见 MiXiT project 了解具体示例。

See MiXiT project for a concrete example.

MockMvc DSL

为了提供更符合 Kotlin 惯例的 API,并允许更好的可发现性(无需使用静态方法),通过 MockMvc Kotlin 扩展提供了一个 Kotlin DSL。

A Kotlin DSL is provided via MockMvc Kotlin extensions in order to provide a more idiomatic Kotlin API and to allow better discoverability (no usage of static methods).

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 Script Templates

Spring Framework 提供了 ScriptTemplateView,它支持 JSR-223,可以使用脚本引擎渲染模板。

Spring Framework provides a ScriptTemplateView which supports JSR-223 to render templates by using script engines.

通过利用 scripting-jsr223 依赖项,可以将此特性用于使用 kotlinx.html DSL 或 Kotlin 多行插值 String 渲染基于 Kotlin 的模板。

By leveraging scripting-jsr223 dependencies, it is possible to use such feature to render Kotlin-based templates with kotlinx.html DSL or Kotlin multiline interpolated String.

build.gradle.kts

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

配置通常使用 ScriptTemplateConfigurerScriptTemplateViewResolver bean 来完成。

Configuration is usually done with ScriptTemplateConfigurer and ScriptTemplateViewResolver beans.

KotlinScriptConfiguration.kt

@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 示例项目了解更详细的信息。

See the kotlin-script-templating example project for more details.

Kotlin multiplatform serialization

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

Kotlin multiplatform serialization is supported in Spring MVC, Spring WebFlux and Spring Messaging (RSocket). The builtin support currently targets CBOR, JSON, and ProtoBuf formats.

要启用它,请遵循 这些说明 以添加相关依赖项和插件。对于 Spring MVC 和 WebFlux,如果它们位于类路径中,则默认将配置 Kotlin 序列化和 Jackson,因为 Kotlin 序列化旨在仅序列化使用 @Serializable 进行注解的 Kotlin 类。对于 Spring Messaging (RSocket),如果您要执行自动配置,请确保类路径中没有 Jackson、GSON 或 JSONB,如果需要 Jackson,请手动配置 KotlinSerializationJsonMessageConverter

To enable it, follow those instructions to add the related dependency and plugin. With Spring MVC and WebFlux, both Kotlin serialization and Jackson will be configured by default if they are in the classpath since Kotlin serialization is designed to serialize only Kotlin classes annotated with @Serializable. With Spring Messaging (RSocket), make sure that neither Jackson, GSON or JSONB are in the classpath if you want automatic configuration, if Jackson is needed configure KotlinSerializationJsonMessageConverter manually.