Search code examples
spring-bootkotlinconfigurationproperties

@ConfigurationProperties without default values in spring boot 3 using Kotlin


I try to implement my first spring boot application using Kotlin. spring-boot version is 3.1.0

I have a configuration class like this(based on https://stackoverflow.com/a/74445643/2674303):

@Configuration
@ConfigurationProperties(prefix = "my.prefix")
data class MyProperties(
    var username: String = "",
    var privateKeyPath: String = "",

This works fine but I don't want to see default values here because they are useless and in java you don't have to have them.

I've found following post: Kotlin & Spring Boot @ConfigurationProperties

And started to apply solutions from there:

1.

import org.springframework.boot.context.properties.bind.ConstructorBinding


@Configuration
@ConfigurationProperties(prefix = "my.prefix")
@ConstructorBinding
data class MyProperties(
    var username: String = "",
    var privateKeyPath: String = "",

I get compilation error:

This annotation is not applicable to target 'class'
@Configuration
@ConfigurationProperties(prefix = "my.prefix")
data class MyProperties {
    lateinit varusername: String = "",
    lateinit var privateKeyPath: String = "",

I receive an error which points to the first fileld:

Property getter or setter expected

Have I missed something ?


Solution

  • This works:

    @ConfigurationProperties(prefix = "my.prefix")
    data class MyProperties {
        lateinit varusername: String = "",
        lateinit var privateKeyPath: String = "",
     ...
    
    @Configuration
    @EnableConfigurationProperties(MyProperties ::class)
    class LdapConnectionPoolConfig(
        private val myProperties : MyProperties 
    ) {
      ....