How to use `@ Value` annotation in spring with Kot...
# spring
m
How to use
@ Value
annotation in spring with Kotlin?
s
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
But I am facing trouble, the value is not getting assigned. I am currently initializing it as lateinit var
s
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
Copy code
@Component
class MongoClient {

    @Value("\${mongodb.host}")
    private lateinit var host: String
}
s
I believe that should work 😕
m
If you are injecting values via constructor. Do you pass some random value while initializing new object everytime?
s
Constructor injection would look like this:
Copy code
@Component
class MongoClient(@Value("\${mongodb.host}") private val host: String) {
    ...
}
m
Yeah but everttime, how you create new object of this class?
s
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
yeah
s
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
Okay. my requirement is to create a mongoclient and return it. Is there a better way to do it?
s
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
cool thanks.
1573 Views