Java, Kotlin, Software Development

Using Spring Autowired in Kotlin

This post shows an example of how to use Spring Autowired to inject an service object into controller objects in Kotlin.

Requirements For Spring and Kotlin

These are Software applications used for this post.

  • IntelliJ IDEA Ultimate 2016.3
    • The Community Edition maybe enough, but we have not tried it.
  • Kotlin Version 1.1
  • Windows 10
  • Spring or Spring Boot

First, we need a project that has both Kotlin and Spring working together. The fastest way to create such project is via the Spring Initialzr and explicitly choosing Kotlin as the language.

Service Codes For Kotlin in Spring

Next, we create a service within that Spring project we generated online for Kotlin. In our example, we are using two Spring beans (or components) – ClientRepo and ClientService. To demonstrate how Spring Autowired works with Kotlin, we autowire the ClientRepo in the ClientService.

Although the ClientRepo is not available on this post, we could create it as follows.

Controller Codes

Then, we use the Spring Autowired annotation in Kotlin to inject the  ClientService object in the IndexController.

In summary, we created three objects and let Spring manage them – ClientRepository, ClientService, and IndexController. With the exception of the ClientRepository, the other two objects has dependency to at least one other object. Therefore, IndexController has a dependency to the ServiceClient which has a dependency on the ClientRepository. We used the Spring Autowired annotation to build that chain of dependencies in Kotlin.

Alternatively, we could do away with the Spring Autowired annotation in Kotlin and retrieve the dependencies from the Spring Context.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like