@ConfigurationProperties without default values in spring boot 3 using Kotlin

1.2k views Asked by At

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 ?

2

There are 2 answers

0
gstackoverflow On BEST ANSWER

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 
) {
  ....
0
scruffy On

After some research here and there I got so use val for config properties like this (for Spring Boot 2.2 and later):

Config class:

@ConfigurationProperties(prefix = "my.prefix")
data class MyConfig @ConstructorBinding constructor(
    val config_one: String,
    val config_two: String,
}

Main Spring class:

@SpringBootApplication
@ConfigurationPropertiesScan
class MySpringApplication