How To Read Properties in Spring Application Kotlin

TL:DR

Play with the code in gitpods!

Gitpod Ready-to-Code

Problem

Every application needs a few properties to work with. This can be your database coordinates, some upstream URL you want to hold, and call later, or any other properties that you might like.

Value Injection

The simplest way of doing this is to use Value injection.

There is a twist in Kotlin though, you need to scape the $ otherwise it is not going to work:

@Value("\${spring.cloud.gcp.project-id}") projectId: String

Using ConfigurationProperties

The simple value injection works most of the time, until you have so many properties that the long list of value injection starts bothering you. There are going to be so many lines of code that you wish there was a way to summaries it and get it out of the way.

Well, there is! Spring provides a fascinating annotation just for this purpose. It is called @ConfigurationProperties!

The way this annotation works is to create a property class and give a namespace for all the properties under a common prefix. For example, let’s look at this class

@Component
@ConfigurationProperties(prefix="redinterface")
data class Properties(
    val name: String)

We created a class called Properties the name of the class doesn’t really matter, what matters is the prefix you give to it.

As you might have noticed properties can be nested. For example Spring properties are usually starts with spring followed by a dot. All of spring properties fall under this prefix so it is easy to understand what belongs to the framework itself. You are encouraged to use a similar approach, and prefix your properties with a nested prefixes. Specially if you are writing a library to be used in other applications. This is a good idea to use your library name as top level prefix and nest everything underneath that.

Anyhow in this case our prefix is redinterface. The property file looks like this.

redinterface.name=red interface

What comes after prefix, is the name of the property. In this case name. Now this all applies to Java too. What is good about Kotlin is that we can use a data class to cut the boilerplate and create a robust immutable property class.

After this step, it is business as usual . You inject your property class to wherever you want and use it! Please note that the property class have to be a component, otherwise you cannot inject it to your Spring beans.

Gitpod Ready-to-Code