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

扩展

Kotlin 扩展 提供了对现有类添加额外功能的能力。Spring 框架的 Kotlin API 使用这些扩展,以向现有的 Spring API 添加新的 Kotlin 特定便利功能。spring-doc.cadn.net.cn

Spring Framework KDoc API 列出了所有可用的 Kotlin 扩展和 DSL。spring-doc.cadn.net.cn

请记住,Kotlin 扩展需要被导入才能使用。这意味着, 例如,GenericApplicationContext.registerBean Kotlin 扩展 只有在导入 org.springframework.context.support.registerBean 时才可用。 话虽如此,与静态导入类似,大多数情况下,IDE 应该会自动建议导入。

例如,Kotlin内联类型参数 为JVM 泛型类型擦除 提供了一种解决方法, Spring框架提供了一些扩展以利用此功能。 这使得新的 RestTemplate 从Spring WebFlux,以及各种其他API的Kotlin API更加完善。spring-doc.cadn.net.cn

其他库,如Reactor和Spring Data,也为它们的API提供了Kotlin扩展,从而整体上提供了更好的Kotlin开发体验。

要检索 Java 中 User 个对象的列表,通常会编写以下代码:spring-doc.cadn.net.cn

Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)

使用 Kotlin 和 Spring 框架的扩展,你可以编写如下内容:spring-doc.cadn.net.cn

val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()

与 Java 一样,Kotlin 中的 users 是强类型,但 Kotlin 的智能类型推断允许使用更简短的语法。spring-doc.cadn.net.cn