69

How to properly initialize ConfigurationProperties in Spring Boot with Kotlin?

Currently I do like in the example below:

 @ConfigurationProperties("app")
 class Config {
     var foo: String? = null
 }

But it looks pretty ugly and actually foo is not a variable, foo is constant value and should be initialized during startup and will not change in the future.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
Sonique
  • 6,670
  • 6
  • 41
  • 60
  • 1
    This is fine the way it is. Spring uses JavaBean binding, so you need getters/setters. `ConfigurationProperties` is for typesafe configuration, it's not a `data` class. – Abhijit Sarkar Aug 30 '17 at 07:53
  • 1
    See https://github.com/spring-projects/spring-boot/issues/8762 which is dicussing about supporting properly immutable data classes for `@ConfigurationProperties`. – Sébastien Deleuze Aug 30 '17 at 13:39
  • (2021) This blog post has a complete guide for using ConfigurationProperties in Kotlin: https://towardsdatascience.com/a-guide-to-use-spring-boots-configurationproperties-annotation-in-kotlin-s-dataclass-1341c63110f4 I've tested it in the latest Spring Boot (2.4.1). Basically, you need to add ConstructorBinding annotation to the data class. And add ConfigurationPropertiesScan annotation to the Application class – aldok Jan 04 '21 at 10:43

10 Answers10

63

With new Spring Boot 2.2 you can do like so:

@ConstructorBinding
@ConfigurationProperties(prefix = "swagger")
data class SwaggerProp(
    val title: String, val description: String, val version: String
)

And don't forget to include this in your dependencies in build.gradle.kts:

dependencies {
  annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
}
Dmitry Kaltovich
  • 2,046
  • 19
  • 21
  • 7
    It's my understanding that kapt has replaced annotationProcessor. You would use Kotlin 1.3.50+ and `plugins { ... kotlin("kapt") }` and `kapt(...)` to wrap the dependency string instead of `annotationProcessor(...)` – Matt Kerr Nov 19 '19 at 18:18
55

Here is how I have it working with my application.yml file.

myconfig:
  my-host: ssl://example.com
  my-port: 23894
  my-user: user
  my-pass: pass

Here is the kotlin file:

@Configuration
@ConfigurationProperties(prefix = "myconfig")
class MqttProperties {
    lateinit var myHost: String
    lateinit var myPort: String
    lateinit var myUser: String
    lateinit var myPass: String    
}

This worked great for me.

Ray Hunter
  • 15,137
  • 5
  • 53
  • 51
  • 2
    After some research this seems like the most reasonable option. It avoids having repetition with a bit dirty @Value annotation, and will also ensure that configuration is set in properties file (if related config entry is missing, exception will be thrown that the value is not initialized). – AbstractVoid Dec 13 '18 at 14:24
  • 13
    What about primitive types, since `lateinit` is not allowed for them? – Tim Büthe Jan 23 '19 at 09:11
  • 1
    How to access these properties from other Spring `@Service` or other `@Component` classes? – kiltek Aug 14 '19 at 13:06
  • @kiltek you can take the configuration bean that is created and use that bean in other components and services. – Ray Hunter Aug 14 '19 at 14:45
  • 2
    What happens if any of the late init properties here aren't present in the environment - do you get a runtime null pointer exception ? – PaulNUK Jun 09 '20 at 11:42
  • 1
    @PaulNUK you will get an kotlin.UninitializedPropertyAccessException if you try and access the variable without initializing it. – Ray Hunter Jun 10 '20 at 15:30
26

Update: As of Spring Boot 2.2.0, you can use data classes as follows:

@ConstructorBinding
@ConfigurationProperties("example.kotlin")
data class KotlinExampleProperties(
        val name: String,
        val description: String,
        val myService: MyService) {

    data class MyService(
            val apiToken: String,
            val uri: URI
    )
}

For further reference, see the official documentation.


Obsolete as of Spring Boot 2.2.0, Issue closed

As stated in the docs: A "Java Bean“ has to be provided in order to use ConfigurationProperties. This means your properties need to have getters and setters, thus val is not possible at the moment.

Getters and setters are usually mandatory, since binding is via standard Java Beans property descriptors, just like in Spring MVC. There are cases where a setter may be omitted [...]

This has been resolved for Spring Boot 2.2.0, which is supposed to be released soon: https://github.com/spring-projects/spring-boot/issues/8762

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • 2
    Can you give an example on how the application.properties file should look like for the given code sample? I am having a similar scenario where i am not sure how to pass values to constructors with more than one parameter. – fspasovski Jan 02 '20 at 14:12
  • From https://spring.io/guides/tutorials/spring-boot-kotlin/: `example.kotlin.myService.apiToken=YourToken` `example.kotlin.myService.uri=YourUri` – OliverE Apr 19 '21 at 10:32
11

On Spring Boot 2.4.3 with Kotlin 1.4.3 the next approach is no longer working (maybe because of a bug):

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.EnableConfigurationProperties

@SpringBootApplication
@EnableConfigurationProperties(TestProperties::class)
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
}
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding

@ConfigurationProperties(prefix = "test")
@ConstructorBinding
data class TestProperties(
    val value: String
)

The code above starts working after implying one of the next two approaches:

  1. Add dependency
implementation("org.jetbrains.kotlin:kotlin-reflect")
  1. Update Properties class
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding

@ConfigurationProperties(prefix = "test")
data class TestProperties @ConstructorBinding constructor(
    val value: String
)

The problem happens at the line org/springframework/boot/context/properties/ConfigurationPropertiesBindConstructorProvider.java#68

VlasovArtem
  • 306
  • 5
  • 6
  • Sadly ConstructorBinding doesnt work well with RefreshScope and Spring Boot devs don't want to fix this. I would advice using lateinit var instead. See https://github.com/spring-cloud/spring-cloud-config/issues/1547 – scre_www Oct 01 '21 at 07:59
  • @scre_www: "Spring Boot devs don't want to fix this" - it has already been closed as "won't fix" – snorbi Sep 29 '22 at 16:19
6
@Value("\${some.property.key:}")
lateinit var foo:String

could be used this way

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • 6
    Thanks, for you comment. I know about `@Value` annotation, but I do not consider this way, because it produces a lot of boilerplate code, `@ConfigurationProperties` definitely better. – Sonique Aug 30 '17 at 06:48
  • This is just a workaround. `@Value` indeed should not be used as a replacement for `@ConfigurationProperties`, since it causes boilerplate code. The way something works ought not to be a right solution. – Buğra Ekuklu Dec 17 '18 at 12:36
6
@ConstructorBinding
@ConfigurationProperties(prefix = "your.prefix")
data class AppProperties (
    val invoiceBaseDir: String,
    val invoiceOutputFolderPdf: String,
    val staticFileFolder: String
)

Don't forget to add @ConfigurationPropertiesScan

@ConfigurationPropertiesScan
class Application

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

And finally the application.properties file:

your.prefix.invoiceBaseDir=D:/brot-files
your.prefix.invoiceOutputFolderPdf=invoices-pdf
your.prefix.staticFileFolder=static-resources
mleister
  • 1,697
  • 2
  • 20
  • 46
6

As of Spring Boot 3.0 you don't need to use @ConstructorBinding annotation anymore.

 @ConfigurationProperties("app")
 data class Config(
     val foo: String = "default foo"
 )

more info here

pixel
  • 24,905
  • 36
  • 149
  • 251
2

application.properties

metro.metro2.url= ######

Metro2Config.kt

@Component
@ConfigurationProperties(prefix = "metro")
data class Metro2PropertyConfiguration(

        val metro2: Metro2 = Metro2()
)

data class Metro2(
    var url: String ?= null
)

build.gradle

Plugins:
id 'org.jetbrains.kotlin.kapt' version '1.2.31'

// kapt dependencies required for IntelliJ auto complete of kotlin config properties class
    kapt "org.springframework.boot:spring-boot-configuration-processor"
    compile "org.springframework.boot:spring-boot-configuration-processor"

EJJ
  • 805
  • 7
  • 13
1

This is how I did it:

application.properties

my.prefix.myValue=1

MyProperties.kt

import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component

@Component
@ConfigurationProperties(prefix = "my.prefix")
class MyProperties
{
    private var myValue = 0
    fun getMyValue(): Int {
        return myValue;
    }

    fun setMyValue(value: Int){
        myValue = value
    }
}

MyService.kt

@Component
class MyService(val myProperties: MyProperties) {
    fun doIt() {
        System.console().printf(myProperties.getMyValue().toString())
    }
}
Qutory
  • 89
  • 6
  • This did not work for me. I also added the annotation `@EnableConfigurationProperties`, but still no success. – Ray Hunter Jun 13 '18 at 02:08
0

In addition to what's already been said, note that val and @ConstructorBinding has some limitations. You cannot alias one variable to another. Let's say you're running in Kubernetes and want to capture the hostname, which is given by the env var HOSTNAME. The easiest way to do this is to apply @Value("\${HOSTNAME}:)" to a property, but it only works for a mutable property and without constructor binding.

See @ConstructorBinding with immutable properties don't work with @Value in Spring Boot Kotlin @ConfigurationProperties.

Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219