Search code examples
springkotlininversion-of-control

Best way to inject component in Spring with Kotlin


For inject a beans with Spring/Kotlin, I know two ways : Passing it into the constructor :

@Service
open class MyService @Autowired constructor(

        @Autowired
        val myRepository: MyRepository

)

Using the 'lateinit' keyword :

@Service
open class MyService {

    @Autowired
    lateinit var myRepository: MyRepository

}

I know the two works, but i'd like to know which one is the best ? Is there some problem I can encounter with one solution and not the other ?

Thank you !


Solution

  • I prefer constructor. Spring no longer requires The @Autowired annotation if there is only one constructor. This way you don't have to make the class open (you do for some Spring things, like @Scheduled but that's another question) or use a var. It's also pretty easy to read.

    This is all you need

    @Service class MyService (private val myRepository: MyRepository)