Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 206
fkurth Avatar asked Sep 15 '17 11:09

fkurth


People also ask

What is the difference between @autowired and @inject annotation in spring?

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

What is the @value annotation used for?

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

What is Autowired in Kotlin?

Kotlin @Autowired constructor injection This annotation instructs the Spring framework to inject the owner dependency into the Car bean.

What is the difference between @autowired and @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).


2 Answers

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.

like image 165
anstue Avatar answered Sep 17 '22 15:09

anstue


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

should be

@Value("\${cacheTimeSeconds}") val cacheTimeSeconds: Int? = null 
like image 24
qwert_ukg Avatar answered Sep 18 '22 15:09

qwert_ukg