Blazerg
Blazerg

Reputation: 849

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

Upvotes: 0

Views: 424

Answers (2)

João Dias
João Dias

Reputation: 17500

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

Upvotes: 4

Nikky
Nikky

Reputation: 518

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

Upvotes: 1

Related Questions