1. 概述

2023 年初,Spring 生态圈传来一个重磅消息:Spring Framework 5 正式支持 Kotlin。这意味着从 Spring Boot 2.x 开始,Kotlin 成为了官方一级支持的语言。

对于熟悉 JVM 的开发者来说,这并不意外。Pivotal 团队一直以来都对 JVM 语言非常友好,比如 Scala 和 Groovy。如今 Kotlin 也正式加入 Spring 的官方支持,意味着我们可以更顺畅地使用 Kotlin 构建 Spring 应用。

本文将带你一步步构建一个基于 Spring Boot 3.x 的 Kotlin 项目,并展示如何使用 Kotlin 的特性提升开发效率和代码质量。


2. 环境搭建

2.1. 开发环境

Kotlin 支持多种开发方式:

  • IntelliJ IDEA(推荐)
  • Eclipse(需安装 Kotlin 插件)
  • 命令行(适用于 CI/CD)

根据你的开发习惯选择合适的 IDE 并完成配置即可。

2.2. Maven 配置

创建一个 Spring Boot 3.x 项目,修改 pom.xml 文件,添加 Kotlin 支持所需的依赖项:

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib-jre8</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-reflect</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
    <version>2.14.2</version>
</dependency>

同时,指定 Kotlin 源码和测试源码的路径:

<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>

最后,添加 Kotlin Maven 插件以支持编译:

<plugin>
    <artifactId>kotlin-maven-plugin</artifactId>
    <groupId>org.jetbrains.kotlin</groupId>
    <version>1.8.0</version>
    <configuration>
        <compilerPlugins>
            <plugin>spring</plugin>
        </compilerPlugins>
        <jvmTarget>17</jvmTarget>
    </configuration>
    <executions>
        <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
        <execution>
            <id>test-compile</id>
            <phase>test-compile</phase>
            <goals>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-allopen</artifactId>
            <version>1.8.0</version>
        </dependency>
    </dependencies>
</plugin>

注意: Kotlin 插件版本应与 Kotlin 标准库版本保持一致。


3. 启动类配置

接下来,创建 Spring Boot 的启动类:

@SpringBootApplication
class KotlinDemoApplication

fun main(args: Array<String>) {
    SpringApplication.run(KotlinDemoApplication::class.java, *args)
}
  • @SpringBootApplication 是标准的 Spring 注解,和 Java 中完全一致。
  • Kotlin 中类默认为 public,无需额外声明。
  • main 函数作为程序入口,无需写 public static void,只需一行即可。

小贴士: Kotlin 中函数默认为 public static,无需额外声明。


4. 控制器编写

创建一个 REST 接口:

@RestController
class HelloController {

    @GetMapping("/hello")
    fun helloKotlin(): String {
        return "hello world"
    }
}
  • 使用 @RestController 声明为 REST 控制器。
  • 方法体简洁,无需返回类型声明(Kotlin 类型推断)。

接着,编写测试类:

@RunWith(SpringRunner::class)
@SpringBootTest(classes = [KotlinDemoApplication::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class KotlinDemoApplicationTests {

    @Autowired
    lateinit var testRestTemplate: TestRestTemplate

    @Test
    fun whenCalled_shouldReturnHello() {
        val result = testRestTemplate.getForEntity("/hello", String::class.java)

        assertNotNull(result)
        assertEquals(result?.statusCode, HttpStatus.OK)
        assertEquals(result?.body, "hello world")
    }
}

Kotlin 特性: 使用 ? 表示可空类型,强制开发者使用 ?. 操作符进行安全访问。


5. 服务层集成

创建一个服务类:

@Service
class HelloService {
    fun getHello(): String = "hello service"
}

将其注入控制器中:

@RestController
class HelloController(private val helloService: HelloService) {

    @GetMapping("/hello-service")
    fun helloKotlinService(): String {
        return helloService.getHello()
    }
}

⚠️ 注意: Kotlin 构造函数注入无需 @Autowired,Spring 会自动识别。


6. Kotlin 数据类

Kotlin 提供了 data class,非常适合用于 DTO:

data class HelloDto(val greeting: String)

这个类自动包含:

  • equals()
  • hashCode()
  • toString()
  • copy() 方法

踩坑提醒: Jackson 默认不支持无参构造函数,因此需要添加 jackson-module-kotlin 依赖。

添加接口:

@GetMapping("/hello-dto")
fun helloDto(): HelloDto = HelloDto("Hello from the dto")

测试方法:

@Test
fun whenCalled_shoudlReturnJSON() {
    val result = testRestTemplate.getForEntity("/hello-dto", HelloDto::class.java)

    assertNotNull(result)
    assertEquals(result?.statusCode, HttpStatus.OK)
    assertEquals(result?.body, HelloDto("Hello from the dto"))
}

7. 总结

通过本文,我们完成了以下内容:

✅ 在 Spring Boot 3.x 中集成 Kotlin
✅ 使用 Kotlin 的语法特性简化代码结构
✅ 利用 data class 提升 DTO 的开发效率
✅ 掌握 Kotlin 与 Spring 的无缝集成方式

Kotlin 凭借其简洁、安全和强大的类型系统,已经成为 Spring 开发的首选语言之一。结合 Spring Boot,你可以快速构建出高质量、可维护的后端服务。

如果你还在犹豫是否要开始使用 Kotlin,现在正是时候!欢迎在评论区分享你使用 Kotlin 构建的应用。

完整源码地址:GitHub


原始标题:Spring Boot and Kotlin