Skip to content

使用 Kotlin 建立 Spring Boot 專案

這是「**Spring Boot 與 Kotlin 入門**」教學的第一部分:


First step 使用 Kotlin 建立 Spring Boot 專案
Second step 將資料類別新增至 Spring Boot 專案
Third step 為 Spring Boot 專案新增資料庫支援
Fourth step 使用 Spring Data CrudRepository 進行資料庫存取

本教學的第一部分將展示如何使用 IntelliJ IDEA 中的專案精靈 (Project Wizard) 建立一個使用 Gradle 的 Spring Boot 專案。

NOTE

本教學不強制使用 Gradle 作為建置系統 (build system)。如果您使用 Maven,也可以遵循相同的步驟。

開始之前

下載並安裝最新版本的 IntelliJ IDEA Ultimate Edition

TIP

如果您使用 IntelliJ IDEA Community Edition 或其他 IDE,可以使用 基於網頁的專案產生器 建立 Spring Boot 專案。

建立 Spring Boot 專案

使用 IntelliJ IDEA Ultimate Edition 中的專案精靈,建立一個新的 Kotlin Spring Boot 專案:

  1. 在 IntelliJ IDEA 中,選取 File | New | Project

  2. 在左側面板中,選取 New Project | Spring Boot

  3. New Project 視窗中指定以下欄位和選項:

    • Name: demo

    • Language: Kotlin

    • Type: Gradle - Kotlin

      TIP

      此選項指定了建置系統和 DSL。

    • Package name: com.example.demo

    • JDK: Java JDK

      NOTE

      本教學使用 Amazon Corretto version 23

      如果您沒有安裝 JDK,可以從下拉式清單中下載。

    • Java: 17

    Create Spring Boot project

  4. 確保您已指定所有欄位,然後點擊 Next

  5. 選取本教學所需用的以下依賴項 (dependencies):

    • Web | Spring Web
    • SQL | Spring Data JDBC
    • SQL | H2 Database

    Set up Spring Boot project

  6. 點擊 Create 以產生並設定專案。

    TIP

    IDE 將會產生並開啟一個新專案。下載和匯入專案依賴項 (project dependencies) 可能需要一些時間。

  7. 在此之後,您可以在「Project view」中看到以下結構:

    Set up Spring Boot project

    所產生的 Gradle 專案與 Maven 的標準目錄佈局相對應:

    • main/kotlin 資料夾下有屬於應用程式的套件和類別。
    • 應用程式的進入點是 DemoApplication.kt 檔案的 main() 方法。

探索專案的 Gradle 建置檔案

開啟 build.gradle.kts 檔案:它是 Gradle Kotlin 建置腳本 (build script),其中包含了應用程式所需的所有依賴項列表。

此 Gradle 檔案對於 Spring Boot 而言是標準的,但它也包含了必要的 Kotlin 依賴項,包括 kotlin-spring Gradle 外掛程式 (plugin) – kotlin("plugin.spring")

以下是完整的腳本,並附有所有部分和依賴項的解釋:

kotlin
// build.gradle.kts
plugins {
    kotlin("jvm") version "1.9.25" // The version of Kotlin to use
    kotlin("plugin.spring") version "1.9.25" // The Kotlin Spring plugin
    id("org.springframework.boot") version "3.4.5"
    id("io.spring.dependency-management") version "1.1.7"
}

group = "com.example"
version = "0.0.1-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jdbc")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin") // Jackson extensions for Kotlin for working with JSON
    implementation("org.jetbrains.kotlin:kotlin-reflect") // Kotlin reflection library, required for working with Spring
    runtimeOnly("com.h2database:h2")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

kotlin {
    compilerOptions {
        freeCompilerArgs.addAll("-Xjsr305=strict") // `-Xjsr305=strict` enables the strict mode for JSR-305 annotations
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

如您所見,Gradle 建置檔案中新增了一些與 Kotlin 相關的構件 (artifacts):

  1. plugins 區塊中,有兩個 Kotlin 構件:

    • kotlin("jvm") – 此外掛程式定義了專案中要使用的 Kotlin 版本
    • kotlin("plugin.spring") – Kotlin Spring 編譯器外掛程式 (compiler plugin),用於為 Kotlin 類別新增 open 修飾符 (modifier),以使其與 Spring Framework 功能相容
  2. dependencies 區塊中,列出了一些與 Kotlin 相關的模組:

    • com.fasterxml.jackson.module:jackson-module-kotlin – 此模組為 Kotlin 類別和資料類別的序列化 (serialization) 和反序列化 (deserialization) 新增支援
    • org.jetbrains.kotlin:kotlin-reflect – Kotlin 反射函式庫 (reflection library)
  3. 在依賴項部分之後,您可以看到 kotlin 外掛程式設定區塊。 您可以在此處為編譯器新增額外引數 (arguments),以啟用或禁用各種語言功能。

中了解更多關於 Kotlin 編譯器選項的資訊。

探索已產生的 Spring Boot 應用程式

開啟 DemoApplication.kt 檔案:

kotlin
// DemoApplication.kt
package com.example.demo

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class DemoApplication

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}
宣告類別 – class DemoApplication

在套件宣告 (package declaration) 和匯入語句 (import statements) 之後,您可以看到第一個類別宣告,class DemoApplication

在 Kotlin 中,如果一個類別不包含任何成員(屬性或函式),您可以省略類別主體({})。

@SpringBootApplication 註解

@SpringBootApplication 註解 是 Spring Boot 應用程式中的一個便捷註解。 它啟用了 Spring Boot 的 自動組態 (auto-configuration)元件掃描 (component scan),並能夠在其「應用程式類別」上定義額外組態。

程式進入點 – main()

main() 函式是應用程式的進入點。

它被宣告為 `DemoApplication` 類別之外的 頂層函式 (top-level function)。`main()` 函式呼叫 Spring 的 `runApplication(*args)` 函式,以使用 Spring Framework 啟動應用程式。

可變引數 – args: Array&lt;String&gt;

如果您檢查 `runApplication()` 函式的宣告,您將看到函式的參數被標記為 `vararg` 修飾符 (modifier)vararg args: String。 這表示您可以向函式傳遞可變數量的字串引數 (String arguments)。

展開運算子 – (*args)

args 是宣告為字串陣列的 `main()` 函式參數。 由於這是一個字串陣列,並且您想將其內容傳遞給函式,因此請使用展開運算子(在陣列前面加上星號 *)。

建立控制器

應用程式已準備好執行,但讓我們先更新其邏輯。

在 Spring 應用程式中,控制器 (controller) 用於處理網頁請求 (web requests)。 在相同的套件中,緊鄰 DemoApplication.kt 檔案,建立 MessageController.kt 檔案,其中包含 MessageController 類別,如下所示:

kotlin
// MessageController.kt
package com.example.demo

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@RestController
class MessageController {
    @GetMapping("/")
    fun index(@RequestParam("name") name: String) = "Hello, $name!"
}
@RestController 註解

您需要告知 Spring MessageController 是一個 REST 控制器 (REST Controller),因此您應該使用 @RestController 註解來標記它。

此註解表示該類別將被元件掃描 (component scan) 識別,因為它與我們的 DemoApplication 類別在同一個套件中。

@GetMapping 註解

@GetMapping 標記了 REST 控制器中實作與 HTTP GET 呼叫相對應的端點 (endpoints) 的函式:

kotlin
@GetMapping("/")
fun index(@RequestParam("name") name: String) = "Hello, $name!"
@RequestParam 註解

函式參數 name 被標記為 @RequestParam 註解。此註解表示方法參數應綁定到網頁請求參數 (web request parameter)。

因此,如果您在根目錄存取應用程式並提供一個名為「name」的請求參數,例如 /?name=<your-value>,則該參數值將用作呼叫 index() 函式的引數。

單一表達式函式 – index()

由於 index() 函式只包含一個語句 (statement),您可以將其宣告為 單一表達式函式 (single-expression function)

這表示可以省略大括號,函式主體在等號 = 之後指定。

函式回傳型別的型別推斷

index() 函式沒有明確宣告回傳型別。相反,編譯器通過查看等號 = 右側語句的結果來推斷 (infer) 回傳型別。

Hello, $name! 表達式 (expression) 的型別是 String,因此函式的回傳型別也是 String

字串樣板 – $name

Hello, $name! 表達式在 Kotlin 中稱為 字串樣板 (String template)

字串樣板是包含嵌入式表達式 (embedded expressions) 的字串常值 (String literals)。

這是字串串聯 (String concatenation) 操作的便捷替代方案。

執行應用程式

Spring 應用程式現在已準備好執行:

  1. DemoApplication.kt 檔案中,點擊 main() 方法旁邊側邊欄 (gutter) 中的綠色 Run 圖示:

    Run Spring Boot application

    TIP

    您也可以在終端機 (terminal) 中執行 ./gradlew bootRun 命令。

    這將在您的電腦上啟動本地伺服器。

  2. 應用程式啟動後,開啟以下 URL:

    text
    http://localhost:8080?name=John

    您應該會看到「Hello, John!」作為回應印出:

    Spring Application response

下一步

在教學的下一部分,您將了解 Kotlin 資料類別以及如何在應用程式中使用它們。

繼續閱讀下一章