how to use spring annotations like @Autowired or @Value in kotlin for primitive types?
You can also use the @Value annotation within the constructor:
class Test(
@Value("\${my.value}")
private val myValue: Long
) {
//...
}
This has the benefit that your variable is final and none-nullable. I also prefer constructor injection. It can make testing easier.
@Value("\${cacheTimeSeconds}") lateinit var cacheTimeSeconds: Int
should be
@Value("\${cacheTimeSeconds}")
val cacheTimeSeconds: Int? = null
I just used Number
instead of Int
like so...
@Value("\${cacheTimeSeconds}")
lateinit var cacheTimeSeconds: Number
The other options are to do what others mentioned before...
@Value("\${cacheTimeSeconds}")
var cacheTimeSeconds: Int? = null
Or you can simply provide a default value like...
@Value("\${cacheTimeSeconds}")
var cacheTimeSeconds: Int = 1
In my case I had to get a property that was a Boolean
type which is primitive in Kotlin, so my code looks like this...
@Value("\${myBoolProperty}")
var myBoolProperty: Boolean = false