Member-only story
Kotlin and Dependency Injection Using Spring Value Annotation
A look at field injection and constructor injection
Spring is a very popular framework in the world of Java, and one of the reasons behind its popularity and high usage rate is its dependency injection mechanism.
Kotlin, on the other hand, is a JVM language created by the team at JetBrains that is considered to be the modern version of Java alongside Scala, for example.
How good would it be to use a modern language with the solid, robust, and time-tested Spring framework?
Fortunately, in January 2017, it was announced that Spring version 5.0 will provide support for Kotlin. So, starting from Spring Boot version 2.x, Kotlin will have their first-class support. This is fantastic!
Spring @Value Annotation
This tutorial will walk you through how to use Spring @Value
annotation in your Kotlin Spring Boot application.
TL;DR: Please see the GitHub repo.
What is @Value annotation?
Spring @Value
annotation allows you to inject values into fields or components in your Spring application — or in other words, in your Spring-managed beans. It can inject values at the constructor, field, or method parameter level.
Alternative to @Value annotation
If you are already familiar with the @Value
annotation, I’d suggest you check out the @ConfigurationProperties
annotation for a different way to inject configuration values. @ConfigurationProperties
is designed for structured objects (e.g. data class
).
Create a Basic Kotlin Spring Boot Project
The easiest way to start a Kotlin Spring Boot project is via Spring Initializr. I personally like the clean design of the UI and just want to highlight the fact that they provide the Dark Mode option.
This is how it looks like when you visit the website: