Getting Started with Dependency Injection in Spring Boot
Mohamed Ezzat
Senior Software Engineer | Java Developer at Deloitte Inovation Hub | Backend Developer
Dependency Injection (DI) is one of the core concepts in Spring Boot, which helps in managing the lifecycle of objects and injecting their dependencies at runtime. It promotes loose coupling and improves testability by allowing developers to swap dependencies without altering the code.
In Spring Boot, we commonly inject dependencies using three main approaches:
Let’s explore each of these,
1. Constructor Injection (Preferred Method)
Constructor injection is now considered the best practice for injecting dependencies in Spring Boot. Spring automatically wires dependencies through the constructor, and you don’t need the @Autowired annotation. This approach also makes the dependency explicit, aiding in testing and clarity.
@Service
public class MyService {
private final MyRepository myRepository;
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
In this example, Spring automatically injects MyRepository into MyService without needing the @Autowired annotation. It is more concise and less error-prone.
2. Setter Injection
Setter injection allows Spring to inject dependencies via a setter method. This can be useful when you want to make some dependencies optional or mutable.
@Service
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
Although still useful in certain cases, setter injection is less commonly used compared to constructor injection.
领英推荐
3. Field Injection (Less Preferred)
Field injection is another way to inject dependencies, but it is generally discouraged because it makes testing harder and violates the principle of immutability.
@Service
public class MyService {
@Autowired
private MyRepository myRepository;
}
While this method is concise, it's recommended to avoid using field injection, especially for complex services, as it makes your code tightly coupled and less testable.
Why Constructor Injection is Preferred
Summary
In Spring Boot, it’s recommended to use constructor injection as it provides immutability, better testability, and cleaner code. While setter and field injections are still available, they should be used based on specific scenarios. Additionally, keep in mind that @Autowired has been deprecated for constructor injection, as Spring now automatically handles this for you.
By following these practices, you’ll ensure a clean, maintainable, and scalable Spring Boot application!
This article is concise and provides a clear guide on how to approach DI in modern Spring Boot applications.