springkotlinautowiredkotlin-null-safetykotlin-interop

how to use spring annotations like @Autowired or @Value in kotlin for primitive types?


Autowiring a non-primitive with spring annotations like bellow works:

@Autowired
lateinit var metaDataService: MetaDataService

But this doesn't work:

@Value("\${cacheTimeSeconds}")
lateinit var cacheTimeSeconds: Int

Error:

lateinit modifier is not allowed for primitive types.

How to autowire primitve properties into Kotlin classes?


Solution

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