Dependency Injection in Spring
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 and 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. You can place @Autowired on constructors, methods, and properties to indicate where Spring should inject dependencies.
Setter Dependency Injection
Setter-based DI involves creating an object using the default constructor and then setting its dependencies through setter methods.
Example:
In this example, @Autowired on the setBread and setCheese methods indicates that Spring should automatically call these setter methods to pass the appropriate Bread and Cheese dependencies. Spring first uses the default constructor to create an instance of Sandwich, then calls these methods to inject the dependencies.
