• Stars
    star
    914
  • Rank 49,973 (Top 1.0 %)
  • Language
    Kotlin
  • Created over 6 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Building web applications with Spring Boot and Kotlin :: Learn how to easily build and test web applications with Spring, Kotlin, Junit 5 and JPA

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.

  1. Select "Gradle - Kotlin" or "Maven" depending on which build tool you want to use

  2. Enter the following artifact coordinates: blog

  3. Add the following dependencies:

    • Spring Web

    • Mustache

    • Spring Data JPA

    • H2 Database

    • Spring Boot DevTools

  4. Click "Generate Project".

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.

build.gradle.kts

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
  id("org.springframework.boot") version "3.0.1"
  id("io.spring.dependency-management") version "1.1.0"
  kotlin("jvm") version "1.8.0"
  kotlin("plugin.spring") version "1.8.0"
  kotlin("plugin.jpa") version "1.8.0"
}

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.

build.gradle.kts

tasks.withType<KotlinCompile> {
  kotlinOptions {
    freeCompilerArgs += "-Xjsr305=strict"
  }
}

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)

build.gradle.kts

dependencies {
  implementation("org.springframework.boot:spring-boot-starter-data-jpa")
  implementation("org.springframework.boot:spring-boot-starter-mustache")
  implementation("org.springframework.boot:spring-boot-starter-web")
  implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
  implementation("org.jetbrains.kotlin:kotlin-reflect")
  runtimeOnly("com.h2database:h2")
  runtimeOnly("org.springframework.boot:spring-boot-devtools")
  testImplementation("org.springframework.boot:spring-boot-starter-test")
}

Recent versions of H2 require special configuration to properly escape reserved keywords like user.

src/main/resources/application.properties

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.

pom.xml

<build>
    <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
    <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <configuration>
          <compilerPlugins>
            <plugin>jpa</plugin>
            <plugin>spring</plugin>
          </compilerPlugins>
          <args>
            <arg>-Xjsr305=strict</arg>
          </args>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-noarg</artifactId>
            <version>${kotlin.version}</version>
          </dependency>
          <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-allopen</artifactId>
            <version>${kotlin.version}</version>
          </dependency>
        </dependencies>
      </plugin>
    </plugins>
  </build>

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)

pom.xml

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mustache</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
  </dependency>
  <dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-reflect</artifactId>
  </dependency>
  <dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib</artifactId>
  </dependency>

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

Understanding the generated Application

src/main/kotlin/com/example/blog/BlogApplication.kt

package com.example.blog

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

@SpringBootApplication
class BlogApplication

fun main(args: Array<String>) {
  runApplication<BlogApplication>(*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<BlogApplication>(*args) is Kotlin idiomatic alternative to SpringApplication.run(BlogApplication::class.java, *args) and can be used to customize the application with following syntax.

src/main/kotlin/com/example/blog/BlogApplication.kt

fun main(args: Array<String>) {
  runApplication<BlogApplication>(*args) {
    setBannerMode(Banner.Mode.OFF)
  }
}

Writing your first Kotlin controller

Let’s create a simple controller to display a simple web page.

src/main/kotlin/com/example/blog/HtmlController.kt

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.

src/main/resources/templates/header.mustache

<html>
<head>
  <title>{{title}}</title>
</head>
<body>

src/main/resources/templates/footer.mustache

</body>
</html>

src/main/resources/templates/blog.mustache

{{> header}}

<h1>{{title}}</h1>

{{> footer}}

Start the web application by running the main function of BlogApplication.kt, and go to http://localhost:8080/, you should see a sober web page with a "Blog" headline.

Testing with JUnit 5

JUnit 5 now used by default in Spring Boot provides various features very handy with Kotlin, including autowiring of constructor/method parameters which allows to use non-nullable val properties and the possibility to use @BeforeAll/@AfterAll on regular non-static methods.

Writing JUnit 5 tests in Kotlin

For the sake of this example, let’s create an integration test in order to demonstrate various features:

  • We use real sentences between backticks instead of camel-case to provide expressive test function names

  • JUnit 5 allows to inject constructor and method parameters, which is a good fit with Kotlin read-only and non-nullable properties

  • This code leverages getForObject and getForEntity Kotlin extensions (you need to import them)

src/test/kotlin/com/example/blog/IntegrationTests.kt

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class IntegrationTests(@Autowired val restTemplate: TestRestTemplate) {

  @Test
  fun `Assert blog page title, content and status code`() {
    val entity = restTemplate.getForEntity<String>("/")
    assertThat(entity.statusCode).isEqualTo(HttpStatus.OK)
    assertThat(entity.body).contains("<h1>Blog</h1>")
  }

}

Test instance lifecycle

Sometimes you need to execute a method before or after all tests of a given class. Like Junit 4, JUnit 5 requires by default these methods to be static (which translates to companion object in Kotlin, which is quite verbose and not straightforward) because test classes are instantiated one time per test.

But Junit 5 allows you to change this default behavior and instantiate test classes one time per class. This can be done in various ways, here we will use a property file to change the default behavior for the whole project:

src/test/resources/junit-platform.properties

junit.jupiter.testinstance.lifecycle.default = per_class

With this configuration, we can now use @BeforeAll and @AfterAll annotations on regular methods like shown in updated version of IntegrationTests above.

src/test/kotlin/com/example/blog/IntegrationTests.kt

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class IntegrationTests(@Autowired val restTemplate: TestRestTemplate) {

  @BeforeAll
  fun setup() {
    println(">> Setup")
  }

  @Test
  fun `Assert blog page title, content and status code`() {
    println(">> Assert blog page title, content and status code")
    val entity = restTemplate.getForEntity<String>("/")
    assertThat(entity.statusCode).isEqualTo(HttpStatus.OK)
    assertThat(entity.body).contains("<h1>Blog</h1>")
  }

  @Test
  fun `Assert article page title, content and status code`() {
    println(">> TODO")
  }

  @AfterAll
  fun teardown() {
    println(">> Tear down")
  }

}

Creating your own extensions

Instead of using util classes with abstract methods like in Java, it is usual in Kotlin to provide such functionalities via Kotlin extensions. Here we are going to add a format() function to the existing LocalDateTime type in order to generate text with the English date format.

src/main/kotlin/com/example/blog/Extensions.kt

fun LocalDateTime.format(): String = this.format(englishDateFormatter)

private val daysLookup = (1..31).associate { it.toLong() to getOrdinal(it) }

private val englishDateFormatter = DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd")
    .appendLiteral(" ")
    .appendText(ChronoField.DAY_OF_MONTH, daysLookup)
    .appendLiteral(" ")
    .appendPattern("yyyy")
    .toFormatter(Locale.ENGLISH)

private fun getOrdinal(n: Int) = when {
  n in 11..13 -> "${n}th"
  n % 10 == 1 -> "${n}st"
  n % 10 == 2 -> "${n}nd"
  n % 10 == 3 -> "${n}rd"
  else -> "${n}th"
}

fun String.toSlug() = lowercase(Locale.getDefault())
    .replace("\n", " ")
    .replace("[^a-z\\d\\s]".toRegex(), " ")
    .split(" ")
    .joinToString("-")
    .replace("-+".toRegex(), "-")

We will leverage these extensions in the next section.

Persistence with JPA

In order to make lazy fetching working as expected, entities should be open as described in KT-28525. We are going to use the Kotlin allopen plugin for that purpose.

With Gradle:

build.gradle.kts

plugins {
  ...
  kotlin("plugin.allopen") version "1.8.0"
}

allOpen {
  annotation("jakarta.persistence.Entity")
  annotation("jakarta.persistence.Embeddable")
  annotation("jakarta.persistence.MappedSuperclass")
}

Or with Maven:

pom.xml

<plugin>
  <artifactId>kotlin-maven-plugin</artifactId>
  <groupId>org.jetbrains.kotlin</groupId>
  <configuration>
    ...
    <compilerPlugins>
      ...
      <plugin>all-open</plugin>
    </compilerPlugins>
    <pluginOptions>
      <option>all-open:annotation=jakarta.persistence.Entity</option>
      <option>all-open:annotation=jakarta.persistence.Embeddable</option>
      <option>all-open:annotation=jakarta.persistence.MappedSuperclass</option>
    </pluginOptions>
  </configuration>
</plugin>

Then we create our model by using Kotlin primary constructor concise syntax which allows to declare at the same time the properties and the constructor parameters.

src/main/kotlin/com/example/blog/Entities.kt

@Entity
class Article(
    var title: String,
    var headline: String,
    var content: String,
    @ManyToOne var author: User,
    var slug: String = title.toSlug(),
    var addedAt: LocalDateTime = LocalDateTime.now(),
    @Id @GeneratedValue var id: Long? = null)

@Entity
class User(
    var login: String,
    var firstname: String,
    var lastname: String,
    var description: String? = null,
    @Id @GeneratedValue var id: Long? = null)

Notice that we are using here our String.toSlug() extension to provide a default argument to the slug parameter of Article constructor. Optional parameters with default values are defined at the last position in order to make it possible to omit them when using positional arguments (Kotlin also supports named arguments). Notice that in Kotlin it is not unusual to group concise class declarations in the same file.

Note
Here we don’t use data classes with val properties because JPA is not designed to work with immutable classes or the methods generated automatically by data classes. If you are using other Spring Data flavor, most of them are designed to support such constructs so you should use classes like data class User(val login: String, …​) when using Spring Data MongoDB, Spring Data JDBC, etc.
Note
While Spring Data JPA makes it possible to use natural IDs (it could have been the login property in User class) via Persistable, it is not a good fit with Kotlin due to KT-6653, that’s why it is recommended to always use entities with generated IDs in Kotlin.

We also declare our Spring Data JPA repositories as following.

src/main/kotlin/com/example/blog/Repositories.kt

interface ArticleRepository : CrudRepository<Article, Long> {
  fun findBySlug(slug: String): Article?
  fun findAllByOrderByAddedAtDesc(): Iterable<Article>
}

interface UserRepository : CrudRepository<User, Long> {
  fun findByLogin(login: String): User?
}

And we write JPA tests to check whether basic use cases work as expected.

src/test/kotlin/com/example/blog/RepositoriesTests.kt

@DataJpaTest
class RepositoriesTests @Autowired constructor(
    val entityManager: TestEntityManager,
    val userRepository: UserRepository,
    val articleRepository: ArticleRepository) {

  @Test
  fun `When findByIdOrNull then return Article`() {
    val johnDoe = User("johnDoe", "John", "Doe")
    entityManager.persist(johnDoe)
    val article = Article("Lorem", "Lorem", "dolor sit amet", johnDoe)
    entityManager.persist(article)
    entityManager.flush()
    val found = articleRepository.findByIdOrNull(article.id!!)
    assertThat(found).isEqualTo(article)
  }

  @Test
  fun `When findByLogin then return User`() {
    val johnDoe = User("johnDoe", "John", "Doe")
    entityManager.persist(johnDoe)
    entityManager.flush()
    val user = userRepository.findByLogin(johnDoe.login)
    assertThat(user).isEqualTo(johnDoe)
  }
}
Note
We use here the CrudRepository.findByIdOrNull Kotlin extension provided by default with Spring Data, which is a nullable variant of the Optional based CrudRepository.findById. Read the great Null is your friend, not a mistake blog post for more details.

Implementing the blog engine

We update the "blog" Mustache templates.

src/main/resources/templates/blog.mustache

{{> header}}

<h1>{{title}}</h1>

<div class="articles">

  {{#articles}}
    <section>
      <header class="article-header">
        <h2 class="article-title"><a href="/article/{{slug}}">{{title}}</a></h2>
        <div class="article-meta">By  <strong>{{author.firstname}}</strong>, on <strong>{{addedAt}}</strong></div>
      </header>
      <div class="article-description">
        {{headline}}
      </div>
    </section>
  {{/articles}}
</div>

{{> footer}}

And we create an "article" new one.

src/main/resources/templates/article.mustache

{{> header}}

<section class="article">
  <header class="article-header">
    <h1 class="article-title">{{article.title}}</h1>
    <p class="article-meta">By  <strong>{{article.author.firstname}}</strong>, on <strong>{{article.addedAt}}</strong></p>
  </header>

  <div class="article-description">
    {{article.headline}}

    {{article.content}}
  </div>
</section>

{{> footer}}

We update the HtmlController in order to render blog and article pages with the formatted date. ArticleRepository and MarkdownConverter constructor parameters will be automatically autowired since HtmlController has a single constructor (implicit @Autowired).

src/main/kotlin/com/example/blog/HtmlController.kt

@Controller
class HtmlController(private val repository: ArticleRepository) {

  @GetMapping("/")
  fun blog(model: Model): String {
    model["title"] = "Blog"
    model["articles"] = repository.findAllByOrderByAddedAtDesc().map { it.render() }
    return "blog"
  }

  @GetMapping("/article/{slug}")
  fun article(@PathVariable slug: String, model: Model): String {
    val article = repository
        .findBySlug(slug)
        ?.render()
        ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "This article does not exist")
    model["title"] = article.title
    model["article"] = article
    return "article"
  }

  fun Article.render() = RenderedArticle(
      slug,
      title,
      headline,
      content,
      author,
      addedAt.format()
  )

  data class RenderedArticle(
      val slug: String,
      val title: String,
      val headline: String,
      val content: String,
      val author: User,
      val addedAt: String)

}

Then, we add data initialization to a new BlogConfiguration class.

src/main/kotlin/com/example/blog/BlogConfiguration.kt

@Configuration
class BlogConfiguration {

  @Bean
  fun databaseInitializer(userRepository: UserRepository,
              articleRepository: ArticleRepository) = ApplicationRunner {

    val johnDoe = userRepository.save(User("johnDoe", "John", "Doe"))
    articleRepository.save(Article(
        title = "Lorem",
        headline = "Lorem",
        content = "dolor sit amet",
        author = johnDoe
    ))
    articleRepository.save(Article(
        title = "Ipsum",
        headline = "Ipsum",
        content = "dolor sit amet",
        author = johnDoe
    ))
  }
}
Note
Notice the usage of named parameters to make the code more readable.

And we also update the integration tests accordingly.

src/test/kotlin/com/example/blog/IntegrationTests.kt

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class IntegrationTests(@Autowired val restTemplate: TestRestTemplate) {

  @BeforeAll
  fun setup() {
    println(">> Setup")
  }

  @Test
  fun `Assert blog page title, content and status code`() {
    println(">> Assert blog page title, content and status code")
    val entity = restTemplate.getForEntity<String>("/")
    assertThat(entity.statusCode).isEqualTo(HttpStatus.OK)
    assertThat(entity.body).contains("<h1>Blog</h1>", "Lorem")
  }

  @Test
  fun `Assert article page title, content and status code`() {
    println(">> Assert article page title, content and status code")
    val title = "Lorem"
    val entity = restTemplate.getForEntity<String>("/article/${title.toSlug()}")
    assertThat(entity.statusCode).isEqualTo(HttpStatus.OK)
    assertThat(entity.body).contains(title, "Lorem", "dolor sit amet")
  }

  @AfterAll
  fun teardown() {
    println(">> Tear down")
  }

}

Start (or restart) the web application, and go to http://localhost:8080/, you should see the list of articles with clickable links to see a specific article.

Exposing HTTP API

We are now going to implement the HTTP API via @RestController annotated controllers.

src/main/kotlin/com/example/blog/HttpControllers.kt

@RestController
@RequestMapping("/api/article")
class ArticleController(private val repository: ArticleRepository) {

  @GetMapping("/")
  fun findAll() = repository.findAllByOrderByAddedAtDesc()

  @GetMapping("/{slug}")
  fun findOne(@PathVariable slug: String) =
      repository.findBySlug(slug) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "This article does not exist")

}

@RestController
@RequestMapping("/api/user")
class UserController(private val repository: UserRepository) {

  @GetMapping("/")
  fun findAll() = repository.findAll()

  @GetMapping("/{login}")
  fun findOne(@PathVariable login: String) =
      repository.findByLogin(login) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "This user does not exist")
}

For tests, instead of integration tests, we are going to leverage @WebMvcTest and Mockk which is similar to Mockito but better suited for Kotlin.

Since @MockBean and @SpyBean annotations are specific to Mockito, we are going to leverage SpringMockK which provides similar @MockkBean and @SpykBean annotations for Mockk.

With Gradle:

build.gradle.kts

testImplementation("org.springframework.boot:spring-boot-starter-test") {
  exclude(module = "mockito-core")
}
testImplementation("org.junit.jupiter:junit-jupiter-api")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
testImplementation("com.ninja-squad:springmockk:4.0.0")

Or with Maven:

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>com.ninja-squad</groupId>
  <artifactId>springmockk</artifactId>
  <version>4.0.0</version>
  <scope>test</scope>
</dependency>

src/test/kotlin/com/example/blog/HttpControllersTests.kt

@WebMvcTest
class HttpControllersTests(@Autowired val mockMvc: MockMvc) {

  @MockkBean
  lateinit var userRepository: UserRepository

  @MockkBean
  lateinit var articleRepository: ArticleRepository

  @Test
  fun `List articles`() {
    val johnDoe = User("johnDoe", "John", "Doe")
    val lorem5Article = Article("Lorem", "Lorem", "dolor sit amet", johnDoe)
    val ipsumArticle = Article("Ipsum", "Ipsum", "dolor sit amet", johnDoe)
    every { articleRepository.findAllByOrderByAddedAtDesc() } returns listOf(lorem5Article, ipsumArticle)
    mockMvc.perform(get("/api/article/").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk)
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("\$.[0].author.login").value(johnDoe.login))
        .andExpect(jsonPath("\$.[0].slug").value(lorem5Article.slug))
        .andExpect(jsonPath("\$.[1].author.login").value(johnDoe.login))
        .andExpect(jsonPath("\$.[1].slug").value(ipsumArticle.slug))
  }

  @Test
  fun `List users`() {
    val johnDoe = User("johnDoe", "John", "Doe")
    val janeDoe = User("janeDoe", "Jane", "Doe")
    every { userRepository.findAll() } returns listOf(johnDoe, janeDoe)
    mockMvc.perform(get("/api/user/").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk)
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("\$.[0].login").value(johnDoe.login))
        .andExpect(jsonPath("\$.[1].login").value(janeDoe.login))
  }
}
Note
$ needs to be escaped in strings as it is used for string interpolation.

Configuration properties

In Kotlin, the recommended way to manage your application properties is to use read-only properties.

src/main/kotlin/com/example/blog/BlogProperties.kt

@ConfigurationProperties("blog")
data class BlogProperties(var title: String, val banner: Banner) {
  data class Banner(val title: String? = null, val content: String)
}

Then we enable it at BlogApplication level.

src/main/kotlin/com/example/blog/BlogApplication.kt

@SpringBootApplication
@EnableConfigurationProperties(BlogProperties::class)
class BlogApplication {
  // ...
}

To generate your own metadata in order to get these custom properties recognized by your IDE, kapt should be configured with the spring-boot-configuration-processor dependency as following.

build.gradle.kts

plugins {
  ...
  kotlin("kapt") version "1.8.0"
}

dependencies {
  ...
  kapt("org.springframework.boot:spring-boot-configuration-processor")
}
Note
Note that some features (such as detecting the default value or deprecated items) are not working due to limitations in the model kapt provides. Also annotation processing is not yet supported with Maven due to KT-18022, see initializr#438 for more details.

In IntelliJ IDEA:

  • Make sure Spring Boot plugin in enabled in menu File | Settings | Plugins | Spring Boot

  • Enable annotation processing via menu File | Settings | Build, Execution, Deployment | Compiler | Annotation Processors | Enable annotation processing

  • Since Kapt is not yet integrated in IDEA, you need to run manually the command ./gradlew kaptKotlin to generate the metadata

Your custom properties should now be recognized when editing application.properties (autocomplete, validation, etc.).

src/main/resources/application.properties

blog.title=Blog
blog.banner.title=Warning
blog.banner.content=The blog will be down tomorrow.

Edit the template and the controller accordingly.

src/main/resources/templates/blog.mustache

{{> header}}

<div class="articles">

  {{#banner.title}}
  <section>
    <header class="banner">
      <h2 class="banner-title">{{banner.title}}</h2>
    </header>
    <div class="banner-content">
      {{banner.content}}
    </div>
  </section>
  {{/banner.title}}

  ...

</div>

{{> footer}}

src/main/kotlin/com/example/blog/HtmlController.kt

@Controller
class HtmlController(private val repository: ArticleRepository,
           private val properties: BlogProperties) {

  @GetMapping("/")
  fun blog(model: Model): String {
    model["title"] = properties.title
    model["banner"] = properties.banner
    model["articles"] = repository.findAllByOrderByAddedAtDesc().map { it.render() }
    return "blog"
  }

  // ...

Restart the web application, refresh http://localhost:8080/, you should see the banner on the blog homepage.

Conclusion

We have now finished to build this sample Kotlin blog application. The source code is available on Github. You can also have a look to Spring Framework and Spring Boot reference documentation if you need more details on specific features.

More Repositories

1

tut-spring-security-and-angular-js

Spring Security and Angular:: A tutorial on how to use Spring Security with a single page application with various backend architectures, ranging from a simple single server to an API gateway with OAuth2 authentication.
TypeScript
1,695
star
2

gs-rest-service

Building a RESTful Web Service :: Learn how to create a RESTful web service with Spring.
Java
1,391
star
3

tut-spring-boot-oauth2

Spring Boot and OAuth2:: A tutorial on "social" login and single sign on with Facebook and Github
Java
905
star
4

gs-spring-boot

Building an Application with Spring Boot :: Learn how to build an application with minimal configuration.
Java
897
star
5

tut-react-and-spring-data-rest

React.js and Spring Data REST :: A tutorial based on the 5-part blog series by Greg Turnquist
JavaScript
884
star
6

gs-spring-boot-docker

Spring Boot with Docker :: Learn how to create a Docker container from a Spring Boot application with Maven or Gradle
Java
619
star
7

gs-messaging-stomp-websocket

Using WebSocket to build an interactive web application :: Learn how to the send and receive messages between a browser and the server over a WebSocket
Java
528
star
8

getting-started-guides

Getting Started Guide template :: The template for new guides and also the place to request them.
Java
519
star
9

tut-rest

Building REST services with Spring :: Learn how to easily build RESTful services with Spring
Java
516
star
10

gs-uploading-files

Uploading Files :: Learn how to build a Spring application that accepts multi-part file uploads.
Java
471
star
11

gs-securing-web

Securing a Web Application :: Learn how to protect your web application with Spring Security.
Java
351
star
12

gs-multi-module

Creating a Multi Module Project :: Learn how to build a library and package it for consumption in a Spring Boot application
Java
329
star
13

gs-serving-web-content

Serving Web Content with Spring MVC :: Learn how to create a web page with Spring MVC and Thymeleaf.
Java
275
star
14

gs-batch-processing

Creating a Batch Service :: Learn how to create a basic batch-driven solution.
Java
243
star
15

gs-accessing-data-jpa

Accessing Data with JPA :: Learn how to work with JPA data persistence using Spring Data JPA.
Java
229
star
16

top-spring-security-architecture

Spring Security Architecture:: Topical guide to Spring Security, how the bits fit together and how they interact with Spring Boot
226
star
17

gs-consuming-rest

Consuming a RESTful Web Service :: Learn how to retrieve web page data with Spring's RestTemplate.
Java
195
star
18

gs-accessing-data-mysql

Accessing data with MySQL :: Learn how to set up and manage user accounts on MySQL and how to configure Spring Boot to connect to it at runtime.
Java
192
star
19

gs-messaging-rabbitmq

Messaging with RabbitMQ :: Learn how to create a simple publish-and-subscribe application with Spring and RabbitMQ.
Java
183
star
20

gs-testing-web

Testing the Web Layer :: Learn how to test Spring Boot applications and MVC controllers.
Java
178
star
21

gs-maven

Building Java Projects with Maven :: Learn how to build a Java project with Maven.
Java
165
star
22

gs-reactive-rest-service

Building a Reactive RESTful Web Service :: Learn how to create a RESTful web service with Reactive Spring and consume it with WebClient.
Java
162
star
23

gs-gradle

Building Java Projects with Gradle :: Learn how to build a Java project with Gradle.
Java
161
star
24

gs-producing-web-service

Producing a SOAP web service :: Learn how to create a SOAP-based web service with Spring.
Java
153
star
25

gs-service-registration-and-discovery

Service Registration and Discovery :: Learn how to register and find services with Eureka
Java
151
star
26

gs-accessing-data-rest

Accessing JPA Data with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.
Java
146
star
27

gs-consuming-web-service

Consuming a SOAP web service :: Learn how to create a client that consumes a WSDL-based service
Java
136
star
28

gs-accessing-data-mongodb

Accessing Data with MongoDB :: Learn how to persist data in MongoDB.
Java
135
star
29

gs-scheduling-tasks

Scheduling Tasks :: Learn how to schedule tasks with Spring.
Java
129
star
30

gs-validating-form-input

Validating Form Input :: Learn how to perform form validation with Spring.
Java
124
star
31

gs-rest-service-cors

Enabling Cross Origin Requests for a RESTful Web Service :: Learn how to create a RESTful web service with Spring that support Cross-Origin Resource Sharing (CORS).
Java
110
star
32

gs-crud-with-vaadin

Creating CRUD UI with Vaadin :: Use Vaadin and Spring Data JPA to build a dynamic UI
Java
108
star
33

gs-gateway

Building a Gateway :: Learn how to configure a gateway
Java
106
star
34

gs-authenticating-ldap

Authenticating a User with LDAP :: Learn how to secure an application with LDAP.
Java
97
star
35

gs-messaging-jms

Messaging with JMS :: Learn how to publish and subscribe to messages using a JMS broker.
Java
90
star
36

gs-async-method

Creating Asynchronous Methods :: Learn how to create asynchronous service methods.
Java
86
star
37

gs-relational-data-access

Accessing Relational Data using JDBC with Spring :: Learn how to access relational data with Spring.
Java
80
star
38

gs-messaging-redis

Messaging with Redis :: Learn how to use Redis as a message broker.
Java
80
star
39

gs-actuator-service

Building a RESTful Web Service with Spring Boot Actuator :: Learn how to create a RESTful Web service with Spring Boot Actuator.
Java
74
star
40

gs-rest-hateoas

Building a Hypermedia-Driven RESTful Web Service :: Learn how to create a hypermedia-driven RESTful Web service with Spring.
Java
73
star
41

gs-accessing-mongodb-data-rest

Accessing MongoDB Data with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.
Java
70
star
42

gs-caching

Caching Data with Spring :: Learn how to cache data in memory with Spring
Java
67
star
43

gs-centralized-configuration

Centralized Configuration :: Learn how to manage application settings from an external, centralized source
Java
58
star
44

gs-accessing-data-r2dbc

Accessing data with R2DBC :: Learn how to access relational data with the reactive protocol R2DBC
Java
47
star
45

gs-spring-boot-kubernetes

Spring Boot Kubernetes :: Deploy a Spring Boot application to Kubernetes :: spring-boot,spring-framework
Java
46
star
46

tut-spring-webflux-kotlin-rsocket

Spring Boot with Kotlin Coroutines and RSocket :: Build a chat application with Reactive Web services from Spring, Kotlin, WebFlux and RSocket
JavaScript
45
star
47

gs-handling-form-submission

Handling Form Submission :: Learn how to create and submit a web form with Spring.
Java
45
star
48

gs-spring-data-reactive-redis

Accessing Data Reactively with Redis :: Learn how to reactively interface with Redis and Spring Data
Java
35
star
49

gs-sts

Working a Getting Started guide with STS :: Learn how to import a Getting Started guide with Spring Tool Suite (STS).
Shell
34
star
50

gs-consuming-rest-angularjs

Consuming a RESTful Web Service with AngularJS :: Learn how to retrieve web page data with AngularJS.
HTML
32
star
51

gs-accessing-data-neo4j

Accessing Data with Neo4j :: Learn how to persist objects and relationships in Neo4j's NoSQL data store.
Java
29
star
52

quoters

Spring Boot quotation service to support REST-based guides
Java
28
star
53

gs-spring-cloud-loadbalancer

Client-Side Load-Balancing with Spring Cloud LoadBalancer :: Dynamically select correct instance for the request :: spring-cloud,spring-cloud-loadbalancer,spring-cloud-commons
Java
28
star
54

gs-convert-jar-to-war

Converting a Spring Boot JAR Application to a WAR :: Learn how to convert your Spring Boot JAR-based application to a WAR file.
Shell
22
star
55

gs-graphql-server

Building a GraphQL service :: Learn how to build a GraphQL service with Spring for GraphQL.
Java
21
star
56

top-spring-on-kubernetes

Spring on Kubernetes :: Topic guide to Spring and Kubernetes
Java
20
star
57

gs-managing-transactions

Managing Transactions :: Learn how to wrap key parts of code with transactions.
Java
19
star
58

gs-messaging-gcp-pubsub

Messaging with Google Cloud Pub/Sub :: Learn how to exchange messages using Spring Integration channel adapters and Google Cloud Pub/Sub
Java
18
star
59

gs-vault-config

Vault Configuration :: Learn how to store and retrieve application configuration details in HashiCorp Vault
Java
16
star
60

getting-started-macros

Collection of macros used to support getting started guides
15
star
61

gs-testing-restdocs

Creating API Documentation with Restdocs :: Learn how to generate documentation for HTTP endpoints using Spring Restdocs
Java
14
star
62

gs-intellij-idea

Working a Getting Started guide with IntelliJ IDEA :: Learn how to work a Getting Started guide with IntelliJ IDEA.
Shell
14
star
63

gs-spring-boot-for-azure

Deploying a Spring Boot app to Azure :: Learn how to deploy a Spring Boot app to Azure.
Shell
14
star
64

gs-contract-rest

Consumer Driven Contracts :: Learn how to with contract stubs and consuming that contract from another Spring application
Java
13
star
65

gs-integration

Integrating Data :: Learn how to build an application that uses Spring Integration to fetch data, process it, and write it to a file.
Java
12
star
66

gs-cloud-circuit-breaker

Spring Cloud Circuit Breaker Guide :: How to Use Spring Cloud Circuit Breaker
Java
12
star
67

gs-accessing-neo4j-data-rest

Accessing Neo4j Data with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.
Java
11
star
68

gs-consuming-rest-jquery

Consuming a RESTful Web Service with jQuery :: Learn how to retrieve web page data with jQuery.
HTML
10
star
69

gs-caching-gemfire

Caching Data with Pivotal GemFire :: Learn how to cache data in GemFire.
Java
9
star
70

gs-accessing-data-gemfire

Accessing Data in Pivotal GemFire :: Learn how to build an application using Gemfire's data fabric.
Java
9
star
71

gs-accessing-vault

Accessing Vault :: Learn how to use Spring Vault to load secrets from HashiCorp Vault
Java
7
star
72

gs-accessing-gemfire-data-rest

Accessing Data in Pivotal GemFire with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.
Java
6
star
73

gs-spring-cloud-stream

Spring Cloud Stream :: Learn how to build and test Spring Cloud Stream Applications with RabbitMQ and Apache Kafka
Java
5
star
74

gs-accessing-data-cassandra

Accessing Data with Cassandra :: Learn how to persist data in Cassandra.
Java
5
star
75

issue-aggregator

List issues from multiple GH repo
Kotlin
3
star
76

gs-spring-cloud-task

Spring Cloud Task :: Learn how to build and test Spring Cloud Task Applications
Java
3
star
77

gs-tanzu-observability

Observability with Spring :: Learn how to send application metrics to Tanzu Observability
Java
3
star
78

drone-aggregator

Get a snapshot view of your CI jobs hosted at drone.io
SCSS
2
star
79

gs-sts-cloud-foundry-deployment

Deploying to Cloud Foundry from STS :: Learn how to deploy a Spring application to Cloud Foundry from STS
Shell
2
star
80

gs-guides-with-vscode

Building a Guide with VS Code :: Learn how to import and work with a Spring Getting Started Guide in VS Code.
Shell
2
star
81

gs-spring-cloud-dataflow

Spring Cloud Data Flow :: Learn how to build, deploy and launch streaming and batch data pipelines using Spring Cloud Data Flow
2
star
82

topical-guides

Spring Topical Guides:: The template for new topical guides on spring.io and also the place to request them
2
star
83

top-observing-graphql-in-action

Observing GraphQL in action :: Tutorial on GraphQL and Observability
Java
1
star