第 1 章:Kotlin 後端生態系與框架選型(Spring Boot vs Ktor)
約 5 分鐘🧋 生活比喻:開餐廳時,「Spring Boot」就像直接租一間設備齊全的中央廚房(水電、冰箱、排油煙機、點餐系統全配好,照規矩就能立刻出菜);「Ktor」則像租一間極簡毛胚屋(輕巧、啟動飛快、每個設備自己選自己裝,想做什麼全由你決定)。
1. Spring Boot vs Ktor:真實專案怎麼選?
在 Kotlin 後端開發中,90% 的選擇都落在 Spring Boot (3.x+) 與 Ktor 之間。這不是「誰比較強」,而是「團隊規模與場景適配」:
| 比較維度 | Spring Boot (Kotlin) | Ktor (JetBrains 官方) |
|---|---|---|
| 定位 | 全功能企業級框架(Batteries included) | 輕量、非阻塞、Kotlin 原生微服務框架 |
| 併發模型 | 傳統 Thread-per-request / WebFlux / Virtual Threads (Java 21+) / Coroutines | 全面原生 Kotlin Coroutines |
| 生態系 | 極度龐大(Spring Security, Data JPA, Batch, Cloud, Actuator) | 較精簡,常需自行組合 Exposed / jOOQ / Koin / Micrometer |
| 啟動速度 & 記憶體 | 較重(啟動約 2~6 秒,記憶體 250MB+,除非用 GraalVM Native) | 極輕快(啟動 < 1 秒,記憶體 ~60-120MB) |
| 學習曲線與踩坑 | 很多「魔法註解(Annotation + Proxy)」,出錯時需懂 Spring AOP/生命週期 | 顯式 DSL 寫法,沒有魔法代理,程式碼流向一目了然 |
| 最適合 | 中大型商業系統、金融電商、團隊多人協作、需要快速整合現成企業元件 | 高併發 I/O Gateway、BFF (Backend for Frontend)、輕量微服務、KMM 共用模組 |
💡 資深工程師經驗談
- 如果團隊超過 5 人、且有 Java 背景同事:選 Spring Boot + Kotlin,因為架構標準化、新人容易上手、企業需求(排程、權限、監控)幾乎都有成熟套件。
- 如果是寫高吞吐量的 API Gateway / BFF / WebSocket 伺服器,或希望從頭到尾純 Kotlin Coroutines:選 Ktor + Exposed/jOOQ + Koin,沒有反射代理地雷,效能與記憶體表現極佳。
- Java 21+ Virtual Threads(Project Loom)出來後還需要 Coroutines 嗎?
Virtual Threads 解決了「阻塞 I/O 卡住作業系統執行緒」的問題,但 Coroutines 依然在「Structured Concurrency(結構化取消)」、「
Flow非同步資料流」、「select/Channel併發編排」上更有優勢。Spring Boot 3.2+ 已經同時支援兩者!
2. 專案分層架構:不要把所有邏輯都塞在 Controller 或 Service
一個可長期維護的 Kotlin 後端服務,通常切分為四層(依賴方向由外向內):
[ HTTP / gRPC / Kafka Consumer ] ← Presentation / Transport Layer (Controller, DTO, Validation)
│
▼
[ UseCase / Application Service ] ← Business Flow (Transaction 邊界, 編排流程)
│
▼
[ Domain Model / Rules ] ← 核心業務規則 (純 Kotlin, 不依賴框架!)
│
▼
[ Repository / HTTP Client ] ← Infrastructure Layer (DB, Redis, 第三方 API)
3. 好的做法 vs 不好的做法
❌ Bad:Controller 直接注入 Repository、操作 DB Entity 並寫業務判斷
@RestController
class BadOrderController(private val orderRepo: OrderRepository) {
@PostMapping("/orders")
fun create(@RequestBody order: OrderEntity): OrderEntity {
// ❌ 1. 直接把 DB Entity 當成 API Request/Response(資安與耦合災難)
// ❌ 2. 業務邏輯散落在 Controller,無法在 Kafka Consumer 或排程中重用
if (order.amount <= 0) throw RuntimeException("金額錯誤")
return orderRepo.save(order)
}
}
✅ Good:清楚的分層 + 專用的 Request / Response DTO
@RestController
@RequestMapping("/api/v1/orders")
class OrderController(
private val createOrderUseCase: CreateOrderUseCase
) {
@PostMapping
fun create(
@Valid @RequestBody request: CreateOrderRequest
): ResponseEntity<OrderResponse> {
val result = createOrderUseCase.execute(request.toCommand())
return ResponseEntity
.status(HttpStatus.CREATED)
.body(OrderResponse.from(result))
}
}
🔍 本章 Code Review 重點
- Controller / Ktor Route 裡有沒有直接出現
Repository或 SQL/ORM 查詢?- 必須透過 Service / UseCase 層隔離,保持傳輸層只負責「收參數、驗證、呼叫 UseCase、轉成 HTTP 回應」。
- Domain 層有沒有 import
org.springframework.*或io.ktor.*?- 核心業務規則盡量保持純 Kotlin,未來換框架或寫純 Unit Test 才不會被綁死。
- 建構子注入(Constructor Injection):
- 永遠使用建構子注入,禁止使用
@Autowired lateinit var(這會破壞 Kotlin 不可變性val與測試方便性)。
- 永遠使用建構子注入,禁止使用