- Building web applications with Spring Boot and Kotlin
- Creating a New Project
- Using the Initializr Website
- Using command line
- Using IntelliJ IDEA
- Understanding the Gradle Build
- Plugins
- Compiler options
- Dependencies
- Understanding the Maven Build
- Plugins
- Dependencies
- Understanding the generated Application
- Writing your first Kotlin controller
Building web applications with Spring Boot and Kotlin
This tutorial shows you how to build efficiently a sample blog application by combining the power of Spring Boot and Kotlin.
If you are starting with Kotlin, you can learn the language by reading the reference documentation, following the online Kotlin Koans tutorial or just using Spring Framework reference documentation which now provides code samples in Kotlin.
Spring Kotlin support is documented in the Spring Framework and Spring Boot reference documentation. If you need help, search or ask questions with the spring and kotlin tags on StackOverflow or come discuss in the #spring channel of Kotlin Slack.
Creating a New Project
First we need to create a Spring Boot application, which can be done in a number of ways.
Using the Initializr Website
Visit https://start.spring.io and choose the Kotlin language. Gradle is the most commonly used build tool in Kotlin, and it provides a Kotlin DSL which is used by default when generating a Kotlin project, so this is the recommended choice. But you can also use Maven if you are more comfortable with it. Notice that you can use https://start.spring.io/#!language=kotlin&type=gradle-project-kotlin to have Kotlin and Gradle selected by default.
- Select «Gradle — Kotlin» or «Maven» depending on which build tool you want to use
- Enter the following artifact coordinates: blog
- Add the following dependencies:
- Spring Web
- Mustache
- Spring Data JPA
- H2 Database
- Spring Boot DevTools
The .zip file contains a standard project in the root directory, so you might want to create an empty directory before you unpack it.
Using command line
You can use the Initializr HTTP API from the command line with, for example, curl on a UN*X like system:
$ mkdir blog && cd blog $ curl https://start.spring.io/starter.zip -d language=kotlin -d type=gradle-project-kotlin -d dependencies=web,mustache,jpa,h2,devtools -d packageName=com.example.blog -d name=Blog -o blog.zip
Add -d type=gradle-project if you want to use Gradle.
Using IntelliJ IDEA
Spring Initializr is also integrated in IntelliJ IDEA Ultimate edition and allows you to create and import a new project without having to leave the IDE for the command-line or the web UI.
To access the wizard, go to File | New | Project, and select Spring Initializr.
Follow the steps of the wizard to use the following parameters:
- Artifact: «blog»
- Type: «Gradle — Kotlin» or «Maven»
- Language: Kotlin
- Name: «Blog»
- Dependencies: «Spring Web Starter», «Mustache», «Spring Data JPA», «H2 Database» and «Spring Boot DevTools»
Understanding the Gradle Build
If you’re using a Maven Build, you can skip to the dedicated section.
Plugins
In addition to the obvious Kotlin Gradle plugin, the default configuration declares the kotlin-spring plugin which automatically opens classes and methods (unlike in Java, the default qualifier is final in Kotlin) annotated or meta-annotated with Spring annotations. This is useful to be able to create @Configuration or @Transactional beans without having to add the open qualifier required by CGLIB proxies for example.
In order to be able to use Kotlin non-nullable properties with JPA, Kotlin JPA plugin is also enabled. It generates no-arg constructors for any class annotated with @Entity , @MappedSuperclass or @Embeddable .
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins
Compiler options
One of Kotlin’s key features is null-safety — which cleanly deals with null values at compile time rather than bumping into the famous NullPointerException at runtime. This makes applications safer through nullability declarations and expressing «value or no value» semantics without paying the cost of wrappers like Optional . Note that Kotlin allows using functional constructs with nullable values; check out this comprehensive guide to Kotlin null-safety.
Although Java does not allow one to express null-safety in its type-system, Spring Framework provides null-safety of the whole Spring Framework API via tooling-friendly annotations declared in the org.springframework.lang package. By default, types from Java APIs used in Kotlin are recognized as platform types for which null-checks are relaxed. Kotlin support for JSR 305 annotations + Spring nullability annotations provide null-safety for the whole Spring Framework API to Kotlin developers, with the advantage of dealing with null related issues at compile time.
This feature can be enabled by adding the -Xjsr305 compiler flag with the strict options.
Dependencies
2 Kotlin specific libraries are required (the standard library is added automatically with Gradle) for such Spring Boot web application and configured by default:
- kotlin-reflect is Kotlin reflection library
- jackson-module-kotlin adds support for serialization/deserialization of Kotlin classes and data classes (single constructor classes can be used automatically, and those with secondary constructors or static factories are also supported)
Recent versions of H2 require special configuration to properly escape reserved keywords like user .
spring.jpa.properties.hibernate.globally_quoted_identifiers=true spring.jpa.properties.hibernate.globally_quoted_identifiers_skip_column_definitions=true
Spring Boot Gradle plugin automatically uses the Kotlin version declared via the Kotlin Gradle plugin.
Understanding the Maven Build
Plugins
In addition to the obvious Kotlin Maven plugin, the default configuration declares the kotlin-spring plugin which automatically opens classes and methods (unlike in Java, the default qualifier is final in Kotlin) annotated or meta-annotated with Spring annotations. This is useful to be able to create @Configuration or @Transactional beans without having to add the open qualifier required by CGLIB proxies for example.
In order to be able to use Kotlin non-nullable properties with JPA, Kotlin JPA plugin is also enabled. It generates no-arg constructors for any class annotated with @Entity , @MappedSuperclass or @Embeddable .
$/src/main/kotlin $/src/test/kotlin org.springframework.boot spring-boot-maven-plugin org.jetbrains.kotlin kotlin-maven-plugin jpa spring -Xjsr305=strict org.jetbrains.kotlin kotlin-maven-noarg $ org.jetbrains.kotlin kotlin-maven-allopen $
One of Kotlin’s key features is null-safety — which cleanly deals with null values at compile time rather than bumping into the famous NullPointerException at runtime. This makes applications safer through nullability declarations and expressing «value or no value» semantics without paying the cost of wrappers like Optional . Note that Kotlin allows using functional constructs with nullable values; check out this comprehensive guide to Kotlin null-safety.
Although Java does not allow one to express null-safety in its type-system, Spring Framework provides null-safety of the whole Spring Framework API via tooling-friendly annotations declared in the org.springframework.lang package. By default, types from Java APIs used in Kotlin are recognized as platform types for which null-checks are relaxed. Kotlin support for JSR 305 annotations + Spring nullability annotations provide null-safety for the whole Spring Framework API to Kotlin developers, with the advantage of dealing with null related issues at compile time.
This feature can be enabled by adding the -Xjsr305 compiler flag with the strict options.
Notice also that Kotlin compiler is configured to generate Java 8 bytecode (Java 6 by default).
Dependencies
3 Kotlin specific libraries are required for such Spring Boot web application and configured by default:
- kotlin-stdlib is the Kotlin standard library
- kotlin-reflect is Kotlin reflection library
- jackson-module-kotlin adds support for serialization/deserialization of Kotlin classes and data classes (single constructor classes can be used automatically, and those with secondary constructors or static factories are also supported)
org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-mustache org.springframework.boot spring-boot-starter-web com.fasterxml.jackson.module jackson-module-kotlin org.jetbrains.kotlin kotlin-reflect org.jetbrains.kotlin kotlin-stdlib org.springframework.boot spring-boot-devtools runtime com.h2database h2 runtime org.springframework.boot spring-boot-starter-test test
Understanding the generated Application
package com.example.blog import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class BlogApplication fun main(args: Array) < runApplication(*args) >
Compared to Java, you can notice the lack of semicolons, the lack of brackets on empty class (you can add some if you need to declare beans via @Bean annotation) and the use of runApplication top level function. runApplication(*args) is Kotlin idiomatic alternative to SpringApplication.run(BlogApplication::class.java, *args) and can be used to customize the application with following syntax.
Writing your first Kotlin controller
Let’s create a simple controller to display a simple web page.
package com.example.blog import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping @Controller class HtmlController < @GetMapping("/") fun blog(model: Model): String < model["title"] = "Blog" return "blog" >>
Notice that we are using here a Kotlin extension that allows to add Kotlin functions or operators to existing Spring types. Here we import the org.springframework.ui.set extension function in order to be able to write model[«title»] = «Blog» instead of model.addAttribute(«title», «Blog») . The Spring Framework KDoc API lists all the Kotlin extensions provided to enrich the Java API.
We also need to create the associated Mustache templates.