Dependency injection

suggest change

Dependency 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:


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

Dependencies are provided through the constructor:

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:

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):


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:


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

  1. Always prefer Constructor Injection: Guarantees mandatory dependencies are not null and enables final fields.
  2. Program to Interfaces: Inject interfaces rather than concrete classes to allow runtime variation and test mocking.
  3. Avoid Circular Dependencies: If Class A requires Class B and Class B requires Class A, redesign responsibilities or introduce an event/mediator pattern.
  4. Keep Business Logic Container-Agnostic: Keep core domain logic free of framework-specific annotations whenever possible.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents