对于最新稳定版本,请使用Spring Framework 7.0.1spring-doc.cadn.net.cn

Web

路由器DSL

Spring Framework 自带了三种版本的 Kotlin 路由器 DSL:spring-doc.cadn.net.cn

这些DSL允许你编写干净且符合惯用法的Kotlin代码,构建一个路由器功能实例如下所示: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是程序化的,意味着它允许对豆子进行自定义注册逻辑 通过一个如果表达式,a循环,或任何其他Kotlin构造。这很有用 当你需要根据动态数据(例如数据库)注册路由时,

具体例子请参见MiXiT项目spring-doc.cadn.net.cn

MockMvc DSL

Kotlin DSL 通过以下方式提供莫克麦克Kotlin 扩展以提供更 采用惯用的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 脚本模板

Spring Framework 提供了脚本模板视图该系统支持 JSR-223 通过脚本引擎渲染模板。spring-doc.cadn.net.cn

通过杠杆Scripting-jsr223依赖关系,它 可以使用该功能渲染基于Kotlin的模板,并kotlinx.html DSL或Kotlin多行插值字符串.spring-doc.cadn.net.cn

build.gradle.ktsspring-doc.cadn.net.cn

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

配置通常通过以下方式完成ScriptTemplateConfigurerScriptTemplateViewResolver豆。spring-doc.cadn.net.cn

KotlinScriptConfiguration.ktspring-doc.cadn.net.cn

@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-doc.cadn.net.cn

Kotlin 多平台序列化

自 Spring Framework 5.3 起,Kotlin 的多平台序列化为 支持于Spring MVC、Spring WebFlux和Spring Messaging(RSocket)。内置支持目前针对 CBOR、JSON 和 ProtoBuf 格式。spring-doc.cadn.net.cn

要启用它,请按照这些说明添加相关的依赖和插件。 使用 Spring MVC 和 WebFlux 时,如果 Kotlin 序列化和 Jackson 都处于类路径中,默认配置为 Kotlin 序列化设计仅序列化注释为@Serializable. 使用 Spring 消息(RSocket),如果你想要自动配置,确保 Jackson、GSON 或 JSONB 都不在类路径中, 如果需要 Jackson 配置KotlinSerializationJsonMessageConverter手动下载。spring-doc.cadn.net.cn