Dependency injection
suggest changeDependency Injection (DI) is a software design pattern implementing the Inversion of Control (IoC) principle. Instead of an object constructing or looking up its own dependencies, dependencies are passed ("injected") into the object from the outside.
DI promotes loose coupling, high testability, and the Single Responsibility Principle.
1. The Core Problem: Tightly Coupled Code
Without dependency injection, classes instantiate their dependencies directly:
// Tightly coupled - difficult to test or extend
public class OrderService {
private final EmailService emailService;
private final SqlOrderRepository repository;
public OrderService() {
// Hard-coded dependencies
this.emailService = new EmailService();
this.repository = new SqlOrderRepository();
}
}
Issues with this approach:
OrderServicecannot be unit-tested in isolation without talking to real mail servers and databases.- Swapping the implementation (e.g., switching from SQL to MongoDB or from Email to SMS) requires editing
OrderService.
2. Manual Dependency Injection (Pure Java)
DI does not strictly require a framework. You can achieve clean dependency injection using plain Java and interfaces.
Step 1: Define Interfaces
public interface NotificationService {
void sendNotification(String recipient, String message);
}
public interface OrderRepository {
void save(Order order);
}
Step 2: Implement Concrete Services
public class EmailNotificationService implements NotificationService {
@Override
public void sendNotification(String recipient, String message) {
System.out.println("Email sent to " + recipient + ": " + message);
}
}
public class InMemoryOrderRepository implements OrderRepository {
@Override
public void save(Order order) {
System.out.println("Order saved: " + order.id());
}
}
Step 3: Inject Dependencies via Constructor (Constructor Injection)
public record Order(String id, double total) {}
public class OrderService {
private final NotificationService notificationService;
private final OrderRepository repository;
// Dependencies are supplied externally
public OrderService(NotificationService notificationService, OrderRepository repository) {
this.notificationService = Objects.requireNonNull(notificationService, "notificationService must not be null");
this.repository = Objects.requireNonNull(repository, "repository must not be null");
}
public void processOrder(Order order, String customerEmail) {
repository.save(order);
notificationService.sendNotification(customerEmail, "Order " + order.id() + " confirmed!");
}
}
Step 4: The Composition Root
The application entry point wires the object graph together:
public class Application {
public static void main(String[] args) {
// Compose dependencies
NotificationService notifier = new EmailNotificationService();
OrderRepository repository = new InMemoryOrderRepository();
OrderService orderService = new OrderService(notifier, repository);
orderService.processOrder(new Order("ORD-101", 99.99), "alice@example.com");
}
}
3. Types of Dependency Injection
1. Constructor Injection (Recommended)
Dependencies are provided through the constructor:
- Ensures instances are fully initialized and valid upon creation.
- Fields can be marked
finalfor immutability and thread safety. - Ideal for required dependencies.
public class PaymentProcessor {
private final PaymentGateway gateway;
public PaymentProcessor(PaymentGateway gateway) {
this.gateway = gateway;
}
}
2. Setter / Method Injection
Dependencies are set via setter methods after instantiation:
- Useful for optional dependencies or dynamic reconfiguration.
- Risk: Objects may exist in an incompletely initialized state if callers forget to invoke the setter.
public class ReportGenerator {
private Formatter formatter = new DefaultFormatter();
public void setFormatter(Formatter formatter) {
this.formatter = Objects.requireNonNull(formatter);
}
}
3. Field Injection
Dependencies are injected directly into private fields using reflection and annotations (@Autowired or @Inject):
- Avoid for domain classes: it obscures dependencies, prevents
finalfields, and requires reflection or a DI container to run unit tests.
4. Standard Java DI: Jakarta Inject (JSR 330)
Java defines a standardized DI specification under the jakarta.inject package:
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.inject.Singleton;
@Singleton
public class UserService {
private final UserRepository userRepository;
@Inject
public UserService(@Named("sqlRepo") UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Standard annotations:
@Inject: Identifies injectable constructors, methods, or fields.@Qualifier/@Named: Disambiguates between multiple implementations of the same interface.@Singleton: Indicates a single shared instance per injector context.@Scope: Declares custom lifecycles (e.g., Request, Session).
5. Dependency Injection with Spring Boot
Spring is the most popular Java DI container. Modern Spring best practices favor constructor injection:
package com.example.service;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class BillingService {
private final PaymentGateway paymentGateway;
private final AuditLogger auditLogger;
// Spring automatically resolves and injects parameters; @Autowired is optional on single constructors
public BillingService(@Qualifier("stripeGateway") PaymentGateway paymentGateway,
AuditLogger auditLogger) {
this.paymentGateway = paymentGateway;
this.auditLogger = auditLogger;
}
public void charge(String customerId, double amount) {
paymentGateway.processCharge(customerId, amount);
auditLogger.log("Charged " + amount + " to customer " + customerId);
}
}
6. Testing with Dependency Injection
Because dependencies are injected, unit testing becomes fast and reliable without running databases or network services:
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
class OrderServiceTest {
@Test
void testProcessOrderSendsNotification() {
// Arrange: Mock the dependencies
NotificationService mockNotifier = mock(NotificationService.class);
OrderRepository mockRepo = mock(OrderRepository.class);
OrderService service = new OrderService(mockNotifier, mockRepo);
Order order = new Order("ORD-999", 49.50);
// Act
service.processOrder(order, "test@example.com");
// Assert
verify(mockRepo).save(order);
verify(mockNotifier).sendNotification("test@example.com", "Order ORD-999 confirmed!");
}
}
7. Best Practices
- Always prefer Constructor Injection: Guarantees mandatory dependencies are not
nulland enablesfinalfields. - Program to Interfaces: Inject interfaces rather than concrete classes to allow runtime variation and test mocking.
- Avoid Circular Dependencies: If Class A requires Class B and Class B requires Class A, redesign responsibilities or introduce an event/mediator pattern.
- Keep Business Logic Container-Agnostic: Keep core domain logic free of framework-specific annotations whenever possible.