Web

Router DSL

Spring 框架帶有一個 Kotlin router DSL,提供 3 種風格

這些 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

Kotlin DSL 是透過 MockMvc Kotlin 擴充功能提供的,以便提供更符合 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 Script Templates

Spring 框架提供 ScriptTemplateView,其支援 JSR-223 以使用 Script 引擎渲染樣板。

透過利用 scripting-jsr223 相依性,可以使用此功能,以 kotlinx.html DSL 或 Kotlin 多行內插 String 渲染基於 Kotlin 的樣板。

build.gradle.kts

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

組態通常是使用 ScriptTemplateConfigurerScriptTemplateViewResolver Bean 完成的。

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 範例專案以取得更多詳細資訊。

Kotlin 多平台序列化

Kotlin 多平台序列化 在 Spring MVC、Spring WebFlux 和 Spring Messaging (RSocket) 中受到支援。內建支援目前目標為 CBOR、JSON 和 ProtoBuf 格式。

若要啟用它,請依照 這些指示 新增相關的相依性與外掛程式。使用 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 都位於類別路徑中,則會預設組態它們,因為 Kotlin 序列化旨在僅序列化以 @Serializable 註解的 Kotlin 類別。使用 Spring Messaging (RSocket),如果您想要自動組態,請確保 Jackson、GSON 或 JSONB 都不在類別路徑中,如果需要 Jackson,請手動組態 KotlinSerializationJsonMessageConverter