Part 7 · 1 chapters · ~8 min

Kotlin on Spring

Spring Boot with Kotlin: the kotlin-spring and kotlin-jpa compiler plugins, constructor injection, data classes and JPA entities (and why entities should not be data classes), coroutines in WebFlux controllers, Spring's Kotlin DSLs, configuration properties, testing with SpringBootTest and MockK, and when Spring beats Ktor.

8

A Spring Boot service in Kotlin

code
// build.gradle.kts
plugins { kotlin("plugin.spring") version "2.4.20"; kotlin("plugin.jpa") version "2.4.20" }

@RestController
@RequestMapping("/v1/transfers")
class TransferController(private val transfers: TransferService) {          // constructor injection
    @PostMapping
    suspend fun create(@RequestHeader("Idempotency-Key") key: String, @RequestBody req: CreateTransferRequest): ResponseEntity<Any> =
        when (val r = transfers.create(req, key)) {
            is TransferResult.Ok -> ResponseEntity.status(201).body(r.transfer.toDto())
            is TransferResult.InsufficientFunds -> ResponseEntity.unprocessableEntity().body(mapOf("error" to "insufficient_funds"))
            TransferResult.LimitExceeded -> ResponseEntity.unprocessableEntity().body(mapOf("error" to "limit_exceeded"))
        }
}

// JPA entities: regular classes, not data classes (equals/hashCode on mutable, lazily loaded state breaks Hibernate)
@Entity class TransferEntity(@Id val id: String, var state: String, val amountKobo: Long)
KOTLIN ON SPRING BOOT
the Java ecosystem with Kotlin ergonomics
first-class supportSpring Framework supports Kotlinofficially, including coroutines.kotlin-spring pluginOpens classes for proxies (Springneeds non-final beans).constructor injectionPrimary constructors replace@Autowired fields.suspend controllersWebFlux supports suspend functionsand Flow.JPA caveatsEntities need open classes andno-arg constructors (kotlin-jpaplugin).same production stackEverything in the Java course P10applies.
swipe the figure sideways, or tap expand for full screen
1/4
official support
Spring supports Kotlin officially: null-safety annotations in Spring's API, coroutine support in WebFlux, and Kotlin DSLs for routing and beans.
a first-class pairingcoroutines in WebFlux