has400
has400

Reputation: 49

How to use variables from application.yaml in SpringBoot kotlin

I need to use variables declared in my applications.yaml file, as an example all it is:

num_error:
    value: "error"
    result: 1

And I have a class trying to call it like the following:

@ConfigurationProperties(prefix = "num_error")
@Component
class NumError {
    companion object {
        lateinit var value: String
        lateinit var result: Number
     }
 }

However, when I try and call this class using NumError.value I get an the following error

lateinit property value has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property value has not been initialized

What have I done wrong, why is this error happening?

Upvotes: 0

Views: 2317

Answers (1)

sidgate
sidgate

Reputation: 15244

You do not need to have companion object, and since Spring boot 2.2 you can have ConstructorBinding to make it work.

@ConstructorBinding
@ConfigurationProperties(prefix = "num_error")
data class NumError(
    val value: String, val result: Number
)

Make sure you include following dependency

dependencies {
  annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
}

EDIT

For older versions, define the variables directly in the class instead of companion object.

@Configuration
@ConfigurationProperties(prefix = "num_error")
class NumError {

  var value: String = "some default value",
  var result: Number? = null
} 

Upvotes: 1

Related Questions