skip to Main Content

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).

2

Answers


  1. first of all it seems like you could use @Property(name = "telegram.token")

    and then i would attempt

    @Property(name = "telegram.token")
    lateinit var token: String
        private set
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search