Title
m

Manoj

03/02/2022, 10:25 AM
How to use
@ Value
annotation in spring with Kotlin?
s

Sam

03/02/2022, 10:26 AM
Same as Java, except that because the
$
has special meaning in Kotlin strings, you need to escape it with
\
For example
@Value("\${my.config.property}")
m

Manoj

03/02/2022, 10:28 AM
But I am facing trouble, the value is not getting assigned. I am currently initializing it as lateinit var
s

Sam

03/02/2022, 10:31 AM
Interesting, I haven't come across that problem. I normally inject values into the constructor instead of into
lateinit
properties. Can you share an example of the code?
m

Manoj

03/02/2022, 10:33 AM
@Component
class MongoClient {

    @Value("\${mongodb.host}")
    private lateinit var host: String
}
s

Sam

03/02/2022, 10:36 AM
I believe that should work šŸ˜•
m

Manoj

03/02/2022, 10:36 AM
If you are injecting values via constructor. Do you pass some random value while initializing new object everytime?
s

Sam

03/02/2022, 10:37 AM
Constructor injection would look like this:
@Component
class MongoClient(@Value("\${mongodb.host}") private val host: String) {
    ...
}
m

Manoj

03/02/2022, 10:38 AM
Yeah but everttime, how you create new object of this class?
s

Sam

03/02/2022, 10:39 AM
Spring creates it for you, so you never actually have to call the constructor
Perhaps this is the problem you're encountering with your
lateinit var
Are you trying to create the MongoClient directly via its constructor, like
MongoClient()
?
m

Manoj

03/02/2022, 10:39 AM
yeah
s

Sam

03/02/2022, 10:40 AM
That won't work with Spring; it needs to create the object itself in order for it to be aware of the injected values and properties within it
m

Manoj

03/02/2022, 10:41 AM
Okay. my requirement is to create a mongoclient and return it. Is there a better way to do it?
s

Sam

03/02/2022, 10:44 AM
Depends on your application, but normally, when you need the
MongoClient
, you should get hold of it by injection. This isn't really specific to Kotlin, it's a general Spring topic. I would suggest following a tutorial on Spring dependency injection.
m

Manoj

03/02/2022, 10:46 AM
cool thanks.