Search code examples
kotlinmicronaut

declare global variable in kotlin defaulted to a property value


I am trying to load a global variable in kotlin directly from the application.yml:

telegram:
  token: foo

to achieve this, in my class I've tried this:

@Value("\${telegram.token}")
val botToken: String

But it is throwing an error saying that I need to initialize the property. (For example, this doesn't throw an error but it is not my expected behaviour):

@Value("\${telegram.token}")
val botToken: String = ""

What I want is to inject the config value (foo) into this constant (botToken).


Solution

  • Either add it as a parameter in the constructor of the bean that contains the property:

    class WhateverSpringManagedBeanClass(
        @Value("\${telegram.token}") private val botToken: String
    )
    

    Or try the following (this makes botToken mutable):

    @Value("\${telegram.token}")
    lateinit var botToken: String