Autowiring a non-primitive with spring annotations like
@Autowired lateinit var metaDataService: MetaDataService
works.
But this doesn't work:
@Value("\${cacheTimeSeconds}") lateinit var cacheTimeSeconds: Int
with an error:
lateinit modifier is not allowed for primitive types.
How to autowire primitve properties into kotlin classes?
@Inject and @Autowired both annotations are used for autowiring in your application. @Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application. Sr.
@Value is a Java annotation that is used at the field or method/constructor parameter level and it indicates a default value for the affected argument. It is commonly used for injecting values into configuration variables - which we will show and explain in the next part of the article.
Kotlin @Autowired constructor injection This annotation instructs the Spring framework to inject the owner dependency into the Car bean.
@Bean is just for the metadata definition to create the bean(equivalent to tag). @Autowired is to inject the dependancy into a bean(equivalent to ref XML tag/attribute).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With