Kotlin Support
Kotlin 是一种针对 JVM(和其他平台)的静态类型语言,它允许编写简洁优雅的代码,同时提供 {url-kotlin-docs}/java-interop.html[与用 Java 编写的现有库的互操作性]。
Kotlin is a statically-typed language targeting the JVM (and other platforms) which allows writing concise and elegant code while providing {url-kotlin-docs}/java-interop.html[interoperability] with existing libraries written in Java.
Spring Boot 通过利用其他 Spring 项目(如 Spring Framework、Spring Data 和 Reactor)中的支持提供 Kotlin 支持。有关详细信息,请参阅 {url-spring-framework-docs}/languages/kotlin.html[Spring Framework Kotlin 支持文档]。
Spring Boot provides Kotlin support by leveraging the support in other Spring projects such as Spring Framework, Spring Data, and Reactor. See the {url-spring-framework-docs}/languages/kotlin.html[Spring Framework Kotlin support documentation] for more information.
开始使用 Spring Boot 和 Kotlin 的最简单方法是按照 this comprehensive tutorial进行操作。您可以使用 IntelliJ IDEA 创建新的 Kotlin 项目。如果您需要支持,请随时加入 Slack 上的 #spring 频道或在 Stack Overflow 上使用 spring
和 kotlin
标记提问。
The easiest way to start with Spring Boot and Kotlin is to follow this comprehensive tutorial.
You can create new Kotlin projects by using start.spring.io.
Feel free to join the #spring channel of Kotlin Slack or ask a question with the spring
and kotlin
tags on Stack Overflow if you need support.
Requirements
Spring Boot 至少需要 Kotlin 1.7.x,并通过依赖项管理管理一个合适的 Kotlin 版本。要使用 Kotlin,org.jetbrains.kotlin:kotlin-stdlib
和 org.jetbrains.kotlin:kotlin-reflect
必须存在于类路径中。也可以使用 kotlin-stdlib
变体 kotlin-stdlib-jdk7
和 kotlin-stdlib-jdk8
。
Spring Boot requires at least Kotlin 1.7.x and manages a suitable Kotlin version through dependency management.
To use Kotlin, org.jetbrains.kotlin:kotlin-stdlib
and org.jetbrains.kotlin:kotlin-reflect
must be present on the classpath.
The kotlin-stdlib
variants kotlin-stdlib-jdk7
and kotlin-stdlib-jdk8
can also be used.
自 Kotlin classes are final by default 起,您可能希望配置 {url-kotlin-docs}/compiler-plugins.html#spring-support[kotlin-spring] 插件以自动打开带有 Spring 注释的类,这样它们就可以被代理。
Since Kotlin classes are final by default, you are likely to want to configure {url-kotlin-docs}/compiler-plugins.html#spring-support[kotlin-spring] plugin in order to automatically open Spring-annotated classes so that they can be proxied.
Jackson’s Kotlin module是 Kotlin 中序列化/反序列化 JSON 数据所必需的。在类路径中找到时会自动注册它。如果存在 Jackson 和 Kotlin,但不存在 Jackson Kotlin 模块,则会记录一个警告消息。
Jackson’s Kotlin module is required for serializing / deserializing JSON data in Kotlin. It is automatically registered when found on the classpath. A warning message is logged if Jackson and Kotlin are present but the Jackson Kotlin module is not.
如果在 start.spring.io上自举 Kotlin 项目,则默认情况下会提供这些依赖项和插件。 |
These dependencies and plugins are provided by default if one bootstraps a Kotlin project on start.spring.io. |
Null-safety
Kotlin 的一项主要功能是 {url-kotlin-docs}/null-safety.html[null-safety]。它在编译时处理 null`值,而不是将问题推迟到运行时并遇到 `NullPointerException
。这有助于消除常见的漏洞根源,而无需付出像 `Optional`这样的包装的代价。Kotlin 还允许将函数式构造与可空值一起使用,如 comprehensive guide to null-safety in Kotlin所示。
One of Kotlin’s key features is {url-kotlin-docs}/null-safety.html[null-safety].
It deals with null
values at compile time rather than deferring the problem to runtime and encountering a NullPointerException
.
This helps to eliminate a common source of bugs without paying the cost of wrappers like Optional
.
Kotlin also allows using functional constructs with nullable values as described in this comprehensive guide to null-safety in Kotlin.
尽管 Java 不允许在类型系统中表达空安全,但 Spring Framework、Spring Data 和 Reactor 现在通过工具友好的注释提供了其 API 的空安全。默认情况下,Kotlin 中使用的 Java API 中的类型被识别为 {url-kotlin-docs}/java-interop.html#null-safety-and-platform-types[平台类型],因此对其放松了空检查。{url-kotlin-docs}/java-interop.html#jsr-305-support[Kotlin 对 JSR 305 注释的支持]与可空性注释相结合,为 Kotlin 中的 Spring API 提供了空安全。
Although Java does not allow one to express null-safety in its type system, Spring Framework, Spring Data, and Reactor now provide null-safety of their API through tooling-friendly annotations. By default, types from Java APIs used in Kotlin are recognized as {url-kotlin-docs}/java-interop.html#null-safety-and-platform-types[platform types] for which null-checks are relaxed. {url-kotlin-docs}/java-interop.html#jsr-305-support[Kotlin’s support for JSR 305 annotations] combined with nullability annotations provide null-safety for the related Spring API in Kotlin.
可以通过添加带有以下选项的 -Xjsr305`编译器标志对 JSR 305 检查进行配置: `-Xjsr305={strict|warn|ignore}
。默认行为与 `-Xjsr305=warn`相同。 `strict`值需要在从 Spring API 推断的 Kotlin 类型中考虑空安全性,但应了解 Spring API 可空性声明即使在次要版本之间也可能会发生变化,将来可能会增加更多检查)。
The JSR 305 checks can be configured by adding the -Xjsr305
compiler flag with the following options: -Xjsr305={strict|warn|ignore}
.
The default behavior is the same as -Xjsr305=warn
.
The strict
value is required to have null-safety taken in account in Kotlin types inferred from Spring API but should be used with the knowledge that Spring API nullability declaration could evolve even between minor releases and more checks may be added in the future).
泛型类型参数、可变参数和数组元素的可空性尚不受支持。有关最新信息,请参见 SPR-15942。还要注意 Spring Boot 自身的 API {url-github-issues}/10712[尚未注释]。
Generic type arguments, varargs and array elements nullability are not yet supported. See SPR-15942 for up-to-date information. Also be aware that Spring Boot’s own API is {url-github-issues}/10712[not yet annotated].
Kotlin API
runApplication
Spring Boot 提供了一种惯用的方式来运行具有 `runApplication<MyApplication>(*args)`的应用程序,如下例所示:
Spring Boot provides an idiomatic way to run an application with runApplication<MyApplication>(*args)
as shown in the following example:
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class MyApplication
fun main(args: Array<String>) {
runApplication<MyApplication>(*args)
}
这是 `SpringApplication.run(MyApplication::class.java, *args)`的替换项。它还允许自定义应用程序,如下例所示:
This is a drop-in replacement for SpringApplication.run(MyApplication::class.java, *args)
.
It also allows customization of the application as shown in the following example:
runApplication<MyApplication>(*args) {
setBannerMode(OFF)
}
Extensions
Kotlin {url-kotlin-docs}/extensions.html[扩展]提供了扩展现有类并添加额外功能的能力。Spring Boot Kotlin API 利用这些扩展向现有 API 添加新的针对 Kotlin 的便利功能。
Kotlin {url-kotlin-docs}/extensions.html[extensions] provide the ability to extend existing classes with additional functionality. The Spring Boot Kotlin API makes use of these extensions to add new Kotlin specific conveniences to existing APIs.
`TestRestTemplate`扩展与 Spring Framework 为 Spring Framework 中 `RestOperations`提供的扩展类似。除其他外,这些扩展使得利用 Kotlin 具象化类型参数成为可能。
TestRestTemplate
extensions, similar to those provided by Spring Framework for RestOperations
in Spring Framework, are provided.
Among other things, the extensions make it possible to take advantage of Kotlin reified type parameters.
Dependency management
为了避免在类路径上混合不同版本的 Kotlin 依赖项,Spring Boot 导入了 Kotlin BOM。
In order to avoid mixing different versions of Kotlin dependencies on the classpath, Spring Boot imports the Kotlin BOM.
通过 Maven,可以通过设置 `kotlin.version`属性来自定义 Kotlin 版本,并为 `kotlin-maven-plugin`提供了插件管理。通过 Gradle,Spring Boot 插件会自动将 `kotlin.version`与 Kotlin 插件版本保持一致。
With Maven, the Kotlin version can be customized by setting the kotlin.version
property and plugin management is provided for kotlin-maven-plugin
.
With Gradle, the Spring Boot plugin automatically aligns the kotlin.version
with the version of the Kotlin plugin.
Spring Boot 还通过导入 Kotlin Coroutines BOM 来管理协程依赖项的版本。可以通过设置 `kotlin-coroutines.version`属性来自定义版本。
Spring Boot also manages the version of Coroutines dependencies by importing the Kotlin Coroutines BOM.
The version can be customized by setting the kotlin-coroutines.version
property.
如果使用至少一个对 start.spring.io的 reactive 依赖项在 Kotlin 项目中进行引导,则默认情况下会提供 `org.jetbrains.kotlinx:kotlinx-coroutines-reactor`依赖项。 |
|
@ConfigurationProperties
`@ConfigurationProperties`与 constructor binding结合使用时支持具有不可变 `val`属性的类,如下例所示:
@ConfigurationProperties
when used in combination with constructor binding supports classes with immutable val
properties as shown in the following example:
@ConfigurationProperties("example.kotlin")
data class KotlinExampleProperties(
val name: String,
val description: String,
val myService: MyService) {
data class MyService(
val apiToken: String,
val uri: URI
)
}
要使用注释处理器生成 your own metadata,应该使用 |
To generate your own metadata using the annotation processor, {url-kotlin-docs}/kapt.html[ |
Testing
虽然可以使用 JUnit 4 测试 Kotlin 代码,但默认情况下会提供 JUnit 5,并且建议使用它。JUnit 5 支持对测试类进行一次实例化并对该类的所有测试进行重用。这使得可以在非静态方法中使用 `@BeforeAll`和 `@AfterAll`注释,这非常适合 Kotlin。
While it is possible to use JUnit 4 to test Kotlin code, JUnit 5 is provided by default and is recommended.
JUnit 5 enables a test class to be instantiated once and reused for all of the class’s tests.
This makes it possible to use @BeforeAll
and @AfterAll
annotations on non-static methods, which is a good fit for Kotlin.
要模拟 Kotlin 类,建议使用 MockK。如果你需要 Mockito 特定的 @MockBean
and @SpyBean
annotations的 `MockK`等效项,则可以使用 SpringMockK,它提供了类似的 `@MockkBean`和 `@SpykBean`注释。
To mock Kotlin classes, MockK is recommended.
If you need the MockK
equivalent of the Mockito specific @MockBean
and @SpyBean
annotations, you can use SpringMockK which provides similar @MockkBean
and @SpykBean
annotations.
Resources
Further reading
-
{url-kotlin-docs}[Kotlin language reference]
-
Kotlin Slack (with a dedicated #spring channel)
-
Tutorial: building web applications with Spring Boot and Kotlin
-
A Geospatial Messenger with Kotlin, Spring Boot and PostgreSQL
Examples
-
spring-boot-kotlin-demo: regular Spring Boot + Spring Data JPA project
-
mixit: Spring Boot 2 + WebFlux + Reactive Spring Data MongoDB
-
spring-kotlin-fullstack: WebFlux Kotlin fullstack example with Kotlin2js for frontend instead of JavaScript or TypeScript
-
spring-petclinic-kotlin: Kotlin version of the Spring PetClinic Sample Application
-
spring-kotlin-deepdive: a step by step migration for Boot 1.0 + Java to Boot 2.0 + Kotlin
-
spring-boot-coroutines-demo: Coroutines sample project