Dependency Injection in Spring Boot
Introduction
Welcome to this lesson on Dependency Injection in Spring Boot. So far, we've covered the basics of Spring and Spring Boot, examined the typical project structure, and delved into the important files within a Spring Boot project. We've also discussed core concepts like Inversion of Control (IoC) and Dependency Injection (DI). In our last lesson, we learned how to create simple beans without dependencies. Today, we’ll build on that foundation by learning how to create beans with dependencies, leveraging Spring’s powerful DI capabilities.
Dependency Injection at a Glance
Dependency Injection is a straightforward concept that becomes incredibly powerful when used correctly. Essentially, if you manually instantiate an object, you have a few approaches:
- Use the default constructor and instantiate properties via setters.
- Use a non-default constructor and pass all parameters into it.
- Use the default constructor with reflection to instantiate private class fields.
Spring simplifies this process by searching for dependencies by type, making it easier to wire dependencies into your classes.
To handle this automatic wiring, Spring uses the @Autowired annotation, which marks the points where dependencies should be injected. In Kotlin, you can use val, var, and property injection effectively.
Constructor-based Implicit @Autowired
Constructor-based DI is the preferred method in Kotlin due to its compatibility with the primary constructor paradigm and alignment with immutability principles. This involves passing all dependencies into the constructor to create an object:
In this example, the Salad class uses a primary constructor where the dependencies lettuce and tomato are injected. The @Autowired annotation is omitted because Spring will automatically use the primary constructor for dependency injection when only one constructor is present. Constructor injection is generally preferred in Kotlin for better readability, immutability, and testability.
Constructor-based Explicit @Autowired
Although Spring boot automatically detects only one constructor, you can explicitly mark the constructor with @Autowired:
Here, the @Autowired annotation explicitly marks the constructor, making it clear where Spring should perform the injection.
