kooskoos
kooskoos

Reputation: 4859

Kotlin init not picking up value from @Value

I want to initialise a member variable from a value I pick from ENV but it is not available in init block as it gets picked up after object initialisation

private lateinit var needValueHere: String
@Value("\${CLIENT_ID:NA}")
private val CLIENT_ID: String = ""

init {
    this.needValueHere = this.CLIENT_ID    
}

This is a simplified version of the actual problem. I have verified the value is available in the member functions.

Upvotes: 1

Views: 2101

Answers (1)

Manushin Igor
Manushin Igor

Reputation: 3689

Your object is constructing by the following way:

  • Create object (e.g. call constructor)
  • Via reflection: put dependencies (e.g. fill values under @Autowired, @Value and other annotations).

Your init block is part of constructor, e.g. all Spring-related items aren't initialized here.

How you can fix this:

  • Extract properties to the type-safe configuration (please see official docs here)
  • Use notation of class like below.
  • Create private lateinit var field and don't call it until Spring initialization finishing (this is useful for integration tests, e.g. test methods start only after full warmup). Another option - use kotlin lazy notation. However whole this item couldn't be named as "good code".
class MyService(@Value("\${CLIENT_ID:NA}") private val needValueHere: String) {
   /* */
}

Upvotes: 1

Related Questions