将 Kotlin 集成到现有的 SpringBoot 项目中
依赖
将 Kotlin 添加到 SpringBoot 项目中,需要添加以下依赖:[1]
xml
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
添加插件:
xml
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<sourceDirs>
<sourceDir>src/main/kotlin</sourceDir>
</sourceDirs>
</configuration>
</plugin>
在 src/main/kotlin
目录下创建 Kotlin 文件,结构和 SpringBoot 项目类似。
编写代码
编写简单 Controller controller/KotlinController.kt
:
kotlin
@RestController
@RequestMapping("/kotlin")
class KotlinController {
@GetMapping("/hello")
fun hello(): String {
return "Hello, Kotlin!"
}
}
编写实体类 model/User.kt
:
kotlin
data class User(val id: Long, val name: String)
现在,Java 和 Kotlin 代码可以混合使用。