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.