← Back to Home
Module 1: Design Pattern: Dependency Injection
Module Overview
Learn about the dependency injection design pattern and how it can be used to create more maintainable and testable code.
Learning Objectives
- Understand loose vs tight-coupling and identify how to remedy tight-coupling
- Understand the concept of dependency injection and its benefits
- What problems does it solve for us
- What are the advantages
- Learn how to implement dependency injection manually in Java applications
- Constructor injection: passing dependencies through constructors
- Field injection: setting dependencies directly into fields
- Method injection: passing dependencies through setter methods
- Understand what a dependency graph (or chain) is and how it relates to DI
- Understand what a DI framework is and how it helps simplify dependency management
- Explore how the Spring framework helps with implementing dependency injection
- What is
@Autowire
annotation
- What are
@Component
s and their specializations
- What kinds of components we use in Spring applications
- Practice using Spring DI annotations effectively
- Understand ApplicationContext and its role in Spring's DI container
Code Example: Dependency Injection
// Without Dependency Injection (tight coupling)
public class OrderService {
private final DatabaseRepository repository = new MySQLRepository(); // Tightly coupled
public void createOrder(Order order) {
repository.save(order);
}
}
// With Dependency Injection (loose coupling)
public class OrderService {
private final Repository repository; // Interface reference
// Constructor injection
public OrderService(Repository repository) {
this.repository = repository;
}
public void createOrder(Order order) {
repository.save(order);
}
}
// With Spring Framework
@Service
public class OrderService {
private final Repository repository;
@Autowired // Spring handles the injection
public OrderService(Repository repository) {
this.repository = repository;
}
public void createOrder(Order order) {
repository.save(order);
}
}