All Articles

Setting up a microservice back-end with Spring Boot and Kotlin

Microservices with Spring Boot and Kotlin
Spring and Kotlin make an awesome combination for microservices

After all that frontend work, we now of course would like so have some backend where we can run much more logic, store the data captured in the frontend, and add many more functionalities.

For this, I have chosen to create microservice backends, and this will be the first one. The framework will be Spring Boot, and the coding language will be Kotlin.

In this article, I will go over what these choices mean, and how to set up a simple dummy Controller to test our new application.

Spring Boot

What is Spring Boot?

Spring Boot is an open source Java based framework to create stand-alone, production ready applications. It is the most used framework to create microservices for Java in the world. I will give a short introduction here, and more explanations will follow in further articles of this series.

Microservices

You be asking yourself what microservices are. After all, you may know that not everything is run in the browser, but why should you have multiple applications in the background?

Essentially, microservices are an architecture pattern where you have a multitude of services that are all running independently. If one of them breaks down, chances are that many users will not even notice. Also, spinning that service back up will be much faster, since the application is much more lightweight.

Some advantages of microservices are (there are more than those I list here):

  • Easy deployment
  • Easy scalability (if only one part of the application is heavily used, only this part needs to be scaled)
  • Less configuration
  • Easily updatable, therefore very quick to get into production
  • Testing chunks of code independently
  • API based, so regression works a lot faster also

Naturally, nothing is ever perfect. Microservice architecture does have some disadvantages, such as duplication/redundancy of code. The rise of microservices versus monolithic applications do seem to strongly favor the advantages over the drawbacks.

Spring Boot

As you may assume from microservices, there are generally several services being run. Spring Boot is a framework that is extremely powerful in wiring applications, with minimal configuration. Compared to simple Spring, it requires much less time for setup, maintenance and dependency verifications. A new application can be set up in minutes, as we will see in this article.

Another major advantage of using Spring Boot is the enormous community that is built around it. There are many so-called starters, that have a lot of dependencies packaged up and ready-to-go in your application immediately. You generally needn’t worry about conflicts with others, as Spring handles the dependency management. Finally, while Spring may be mostly used in Java, it is really compatible with any JVM based language, so you can easily use it with Kotlin also.

Kotlin

What is Kotlin

Kotlin is a statically typed programming language and is run on the JVM (Java Virtual Machine). This means it follows the same write once, run anywhere principle. It is fully interoperable with Java, so you can use Java libraries or even have Java classes in the very same Kotlin project. Kotlin has gained some fame when Google announced in May of 2019 that Kotlin has become the preferred programming language for Android apps, thus surpassing Java.

Kotlin can technically also be compiled to JavaScript, and there are some projects that run on React with Kotlin instead of JavaScript. The reason here is the fact that Kotlin is statically typed, so there will be many errors that can be detected by the compiler already.

Kotlin is developed by IDEA, the creators of the, in my opinion, best IDE for JVM based languages. This also means that the people who work on the language are very close to what developers actually want, and they work hard to include those features.

Kotlin has some very nice tutorials to get started and see its amazing advantages. You can find those tutorials here.

Why use Kotlin

This is all very nice, but why use Kotlin? You may already know Java, and while Kotlin is very similar, it’s still a new language, and a new syntax, to learn and master.

Well, Kotlin has taken a very good look at Java, and noticed which features could be improved. Which parts of the language were the most painful for developers, and how did other languages fix them? It has, for instance, put functional programming much more in the foreground, it has removed the most annoying error ever from Java, the notorious NullPointerException. Yes, you read that right - no more NPEs if you use Kotlin correctly!

Here is a non-exhaustive list of advantages of Kotlin:

  • Null safety, and no checked exceptions
  • Extension functions allow you to extend classes that are not in your project with methods
  • Data classes (automatic generation of boilerplate code)
  • Smart casts and type inference
  • Functional programming
  • An enormous amounts of static methods for instantiation (e.g. listOf(), immutableListOf(), etc.)
  • Much more concise code
  • Lightweight coroutines (as opposed to only heavy threads)

Of course, there are Java libraries, such as Lombok, that enable developers some of the functionalities. However, using Lombok will only get you so far, and it can oftentimes give you headaches when certain annotations cannot handle all the complexity you may need. With Kotlin, you have everything built in the language directly, which is always more convenient.

Application Setup

After this introduction to the coding language and the framework, we’ll go over how fast you can set up a project. We will already see the first couple of advantages of Spring Boot, as you will receive some monitoring endpoints without writing a single line of code!

Generate the skeleton

To get started, go to the Spring Initializr. This is an awesome page where you can create the skeleton for your application in seconds. We will choose the following settings:

  • Maven as Project
  • Kotlin as language
  • 2.5.5 as the version

For the project metadata, you can insert how you wish to create the project. As for dependencies, I will use the following:

  • Spring Web (enables everything Web related, e.g. Spring Controllers)
  • Spring Security
  • Spring Boot Actuator (additional endpoints for monitoring and debugging)
  • Spring Data Jpa (for everything database related)
  • Validation
  • Spring cache abstraction

Of course, you can always add more dependencies into the project as time goes on.

Initializr setup
Setup for the initializr

Now, you click on generate, export the zip, and voilà - you have an application!!

If you have a closer look at the code that has been generated, there won’t be much. It’s pretty much this:

@SpringBootApplication
class MoneyManagementApplication

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

Getting the application runnning

However, if you run the application, you’ll see that it actually fails. You may wonder how that’s possible - there’s hardly any code in there, after all!?

Well, here’s where those starters come in. You may think that there’s nothing in it - but your pom.xml has quite some dependencies. One of them is this fellow:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

Now, this dependency will create some Java beans for you. Java beans are complex objects, such as components, services, controllers, and they sometimes need some values to be instantiated. Without those values, the instantiation will fail, which is what happened in here. Notably, in this case, the bean in question is wondering where the database is situated.

So, let’s add those properties!

It may be that your project has been generated with an application.properties file (in the src/main/resources directory). This works, naturally. I’m more a fan of the yaml representation of properties however, so I’ll remove that file and replace it with an application.yaml in the same directory. (If your project has been generated with an application.yaml, then you do not need to worry about that step. Next, we let the application know where the datasource is by adding the following block of properties into your application.yaml:

spring:
  datasource:
    url: jdbc:h2:mem:testdb

Also, in your pom.xml, add the following dependency, as it is required for the DB we will use in the beginning:

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>

This will create an h2, in-memory database. This means that the data will be removed every time that you stop the application, but that’s ok for now.

If you run the app again, it will start. At least, the IDE says it started, but how can you verify? You don’t actually have anything to test, right? Just go to http://localhost:8080 though, and see what happens.

Spring security login
Your app is already protected by a login!

Disabling security and checking actuators

Well, this is interesting. On the one hand, it shows you that your app is already protected, but on the other, how can you even log in? You could create some users, give them access, and then continue. However, that’s already a lot of work before you can start building your app. It’s not ideal, but I’m the same as everyone, and while security is hugely important, it’s not the first topic I’d want to tackle. So let’s turn it off for now, shall we?

You can do this, but modifying the @SpringBootApplication to @SpringBootApplication(exclude = [SecurityAutoConfiguration::class, ManagementWebSecurityAutoConfiguration::class]). This will turn off the default security.

A better option may be by determining antMatchers for your security - I will show this below.

If you start the application again though, and you go back to http://localhost:8080, you will get a 404. Technically that’s a good sign, as that means that something is at least served on that port (you can try with 8081, and that site simply cannot be reached.) So, does that mean that you need to add functionality to verify whether the app is running?

Well, not quite! Remember that actuators dependency, where I mentioned that it adds some monitoring endpoints? Well, if you go to http://localhost:8080/actuator/health, you will get some information about the health of the application. Clearly, the app seems to be UP. (I realize it’s not as pretty anymore as in previous posts, but we’re working on backends now, so it’s already nice that we see something…)

Spring health actuator
Your app is definitely UP!

More information on actuators can be found here. There’s a lot more to them than only showing the application’s health, but this is already a very good way to check if your application is running (for example for a kubernetes liveness check).

Congratulations on running your Spring Boot Kotlin application!!

Alternative to disabling security altogether

Of course, you may argue that disabling security entirely is not ideal, and you’d be absolutely right. So let’s change the way we handle requests to the server.

First, we create a “security” package, in which we add our own security configuration.

package com.mauquoi.moneymanagement.moneymanagement.security

import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.stereotype.Component

@Component
class AppWebSecurityConfigurerAdapter : WebSecurityConfigurerAdapter() {

    override fun configure(web: WebSecurity?) {
        web?.ignoring()?.antMatchers("/actuator/*")
    }
}

This will effectively allow you to go to any page that starts with /actuator (keep in mind that the page must exist though). If you reload /actuator/health, you will still see that the app is UP. If you go to /hello-world though, you will be redirected back to the login page. If you decide to experiment a bit, and you add /hi to the antMatchers for not unauthenticated access, you will still be redirected to the login page. The reason here is that /hi doesn’t actually exist. If you were to now add a simple endpoint for this, as the dummy Controller below, the server would be very glad to greet you again:

@RestController
class MyController {

    @GetMapping("/hi")
    fun hi() : ResponseEntity<String> {
        return ResponseEntity.ok("And hello to you, too!")
    }
}

There you go! You now have the backbone for your very own spring boot application running on Kotlin! Have fun developing!

In the next article, we will create the data layer, cover the database setup with jpa and liquibase, and create the endpoints to query our account information.