Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 134 ยท Testing and Tooling

Spring Boot with Kotlin

Use Spring Boot with Kotlin: the plugins, constructor injection, data classes as DTOs, null safety in controllers, configuration properties and suspend functions in WebFlux.

Spring Boot is the most widely used framework for building JVM web services, and Kotlin is a first-class language there. The Spring team treats Kotlin as an officially supported language: the documentation has Kotlin examples, the project generator at start.spring.io offers Kotlin, and many Spring APIs have Kotlin extensions. Because Kotlin runs on the JVM, everything you know from Java interoperability applies: Spring is simply a big Java library that you call from Kotlin.

Spring Boot needs a running application server, a build tool and downloaded libraries, so none of the Spring code in this lesson can run in the in-browser runner. The Spring snippets are read-only. To still learn the Kotlin ideas that make Spring code short, the TryIt blocks use small stand-ins: plain Kotlin that mimics what the framework does. For the server side in general, see Kotlin on the Server.

Project setup

A Spring Boot project in Kotlin uses Gradle with the Kotlin plugin, plus two compiler plugins that remove friction between Kotlin and Spring:

Kotlin
// read-only example: build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.0"
    kotlin("plugin.spring") version "2.4.0"   // opens Spring-annotated classes
    kotlin("plugin.jpa") version "2.4.0"      // no-arg constructors for JPA entities
    id("org.springframework.boot") version "4.0.0"
    id("io.spring.dependency-management") version "1.1.7"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

Why plugins? Kotlin classes are final by default (see inheritance), but Spring creates proxies for beans (to add transactions, caching, security) by subclassing them. plugin.spring automatically makes classes with Spring annotations (@Component, @Service, @Configuration and others) open, so you do not write open everywhere. plugin.jpa generates the no-argument constructors that JPA needs. jackson-module-kotlin teaches the JSON library to read Kotlin constructors, default values and nullability, and kotlin-reflect is needed for these features.

The application class

The entry point is short because a top-level function replaces the static main:

Kotlin
// read-only example
@SpringBootApplication
class ShopApplication

fun main(args: Array<String>) {
    runApplication<ShopApplication>(*args)
}

runApplication is a Kotlin extension function and *args is the spread operator passing the array as varargs.

Constructor injection, the Kotlin way

In Java, Spring beans often use field injection or long constructors with assignments. In Kotlin, a primary constructor with val parameters is both: the dependencies are declared once, they are immutable and they cannot be forgotten. When a class has one constructor, Spring uses it without any @Autowired.

Kotlin
// read-only example
@Service
class OrderService(
    private val orders: OrderRepository,
    private val prices: PriceCalculator,
)

@RestController
@RequestMapping("/orders")
class OrderController(private val service: OrderService) {

    @GetMapping("/{id}")
    fun find(@PathVariable id: Long): OrderDto =
        service.find(id) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND)
}

Notice service.find(id) ?: throw ...: the Elvis operator turns a missing result into an HTTP 404 in one line. The same idea can be tried without Spring. This stand-in builds a tiny "container" by hand to show why constructor injection is easy to test: dependencies are plain parameters.

Kotlin Constructor injection without a container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because no framework is needed to construct these classes, a unit test can create them directly with a fake PriceCalculator, like the one in Mocking and Test Doubles.

Data classes as DTOs and entities

Request and response bodies are natural data classes: equals, hashCode, toString and copy for free, with immutable val properties. Jackson (with the Kotlin module) fills the constructor, and nullable types and default values describe the contract exactly:

Kotlin
// read-only example
data class CreateOrderRequest(
    val customer: String,
    val items: List<String>,
    val note: String? = null,        // optional in the JSON
)

data class OrderDto(val id: Long, val customer: String, val total: Int)

With the module installed, a JSON body without customer is rejected with a 400 error because the parameter is non-null. In Java you would get a null and a NullPointerException later.

Be careful with data classes as JPA entities. A JPA entity is mutable, has an identity and is often lazily loaded, which fits poorly with data class semantics (generated equals over all fields, copy creating duplicates, toString triggering lazy loading). The common advice is: use a normal class with var properties for entities, define equals and hashCode on the id only, and keep data classes for DTOs.

Kotlin
// read-only example
@Entity
class Customer(
    @Column(nullable = false) var name: String,
    @Id @GeneratedValue var id: Long? = null,
)

This also shows the null-safety rule: the generated id is Long? because it does not exist before the first save.

Configuration properties

Instead of reading values with @Value("${...}") strings, bind a group of settings to an immutable class. A data class with defaults describes the shape and the fallback in one place:

Kotlin
// read-only example
@ConfigurationProperties(prefix = "shop")
data class ShopProperties(
    val currency: String = "EUR",
    val maxItems: Int = 20,
    val supportEmail: String,
)
YAML
# read-only example: application.yml
shop:
  support-email: [email protected]
  max-items: 50

Spring converts support-email to supportEmail and fails at startup if a required value is missing. The stand-in below does the same with a map, to show how defaults and required values behave:

Kotlin Binding settings to a data class (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Idioms that make Spring code shorter

  • Expression bodies and ?: for controller methods, as shown above.
  • Extension functions on Spring types. For example, restClient.get().uri(url).retrieve().body<Order>() uses a reified extension so you do not pass a Class (see reified type parameters).
  • Beans with the DSL. Spring has a Kotlin bean definition DSL and router DSLs (router { GET("/hello") { ... } }) that use lambdas with receivers.
  • Logging. Use a private top-level val log = LoggerFactory.getLogger(...) or a companion object instead of base classes (see logging).
  • Constants and @Value. Prefer @ConfigurationProperties; const val cannot hold configuration that changes between environments.
  • Testing. @SpringBootTest for full tests and plain unit tests with constructors for the rest. A mock library such as MockK fits Kotlin better than Mockito for final classes and coroutines.

Coroutines support

Spring supports Kotlin coroutines in two ways. With Spring WebFlux, a controller method can be a suspend function, and a method that returns Flow<T> streams values. Spring runs the coroutine for the request and handles cancellation if the client disconnects:

Kotlin
// read-only example
@RestController
class QuoteController(private val client: QuoteClient) {

    @GetMapping("/quote/{symbol}")
    suspend fun quote(@PathVariable symbol: String): Quote = client.fetch(symbol)

    @GetMapping("/quotes", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
    fun stream(): Flow<Quote> = client.updates()   // a Flow<Quote> streamed to the client
}

Even in classic Spring MVC (servlet-based), you can use suspend controller methods in recent versions, and Spring Data repositories offer suspend and Flow variants for reactive databases. The practical benefit is that you write sequential-looking code, and several downstream calls can run in parallel with async, as in the stand-in below.

Kotlin A suspend handler calling two services in parallel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Inside coroutineScope, if one call fails the other is cancelled (see structured concurrency), which is exactly what you want in a request handler.

Common problems

  • "Class is final and cannot be proxied". The plugin.spring plugin is missing, or you used an annotation it does not know about. Add open or the allOpen configuration.
  • JSON fails on Kotlin classes. jackson-module-kotlin is missing, so Jackson looks for a no-argument constructor.
  • Nullable platform types. Values from Java APIs may be null although they look non-null. See platform types.
  • Blocking inside a coroutine. Calling a blocking JDBC method from a WebFlux suspend function blocks an event-loop thread. Use withContext(Dispatchers.IO) or a non-blocking driver (see dispatchers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the kotlin("plugin.spring") compiler plugin used?

    Kotlin classes are final by default, and Spring needs to subclass beans to create proxies. The plugin opens annotated classes automatically.
  2. 2. What is the idiomatic way to inject dependencies in a Spring bean written in Kotlin?

    A primary constructor with val parameters declares the dependencies once, keeps them immutable and works without @Autowired when there is a single constructor.
  3. 3. Why does the lesson advise against using data classes as JPA entities?

    Entities are mutable and identified by an id. Content-based equals and toString over all fields, and copy, cause surprises. Use data classes for DTOs.
  4. 4. What can a controller method in Spring WebFlux return when written as a Kotlin function?

    Spring supports suspend functions (one value) and Flow (a stream of values) as controller return types, in addition to Mono and Flux.

Summary

  • Spring Boot supports Kotlin officially; a Gradle build adds plugin.spring, plugin.jpa, jackson-module-kotlin and kotlin-reflect.
  • runApplication<App>(*args) and a top-level main start the application.
  • Use constructor injection with private val parameters; classes stay easy to create in unit tests.
  • Data classes suit DTOs and @ConfigurationProperties; use regular classes for JPA entities.
  • Non-null and nullable types describe required and optional JSON fields; ?: throw maps missing data to an HTTP error.
  • Controllers can be suspend functions or return Flow, and coroutineScope with async runs downstream calls in parallel.
  • Spring code is not runnable here; the stand-ins show the Kotlin ideas behind it.

Next: Jetpack Compose Basics