4 Hours

6. Dependency Injection & Inversion of Control

Core Spring
Sandbox Note: The editor validates your Java and Spring annotation syntax only. It does NOT start a Spring context or perform actual dependency injection. When you see Compilation successful (exit code 0), your code is syntactically correct. Copy it to your local IDE and run ./mvnw spring-boot:run to see DI in action.

Dependency Injection (DI) and Inversion of Control (IoC) are the fundamental concepts that make Spring powerful. They are not Spring-specific — they are design patterns — but Spring implements them brilliantly. Understanding these patterns is essential for writing decoupled, testable Spring applications.

What is Inversion of Control (IoC)?

In traditional programming, your code controls everything. You create objects when you need them using the new keyword. IoC inverts this control — the framework (Spring) controls the lifecycle of objects and your code receives dependencies from the framework.

Java
// Traditional approach (Your code controls everything)
public class OrderService {
    private PaymentService paymentService;

    public OrderService() {
        // You create the dependency
        this.paymentService = new PaymentService();
    }
}

// IoC approach (Spring controls creation)
@Service
public class OrderService {
    private final PaymentService paymentService;

    // Spring calls this constructor and provides the dependency
    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}
To test DI locally: Create a Spring Boot project, add @Service to both classes, and Spring will automatically inject PaymentService into OrderService when you run the application.

What is Dependency Injection?

Dependency Injection is the mechanism that enables IoC. Instead of a class creating its own dependencies, the dependencies are injected from the outside (by the Spring container).

Java
// Types of Dependency Injection in Spring

// 1. Constructor Injection (RECOMMENDED)
@Service
public class UserService {
    private final UserRepository userRepository;
    private final EmailService emailService;

    // Spring 4.3+ - @Autowired is optional when single constructor
    public UserService(UserRepository userRepository, EmailService emailService) {
        this.userRepository = userRepository;
        this.emailService = emailService;
    }
}

// 2. Setter Injection
@Service
public class CartService {
    private InventoryService inventoryService;

    @Autowired
    public void setInventoryService(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }
}

// 3. Field Injection (NOT RECOMMENDED - hard to test)
@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;
}

The Spring IoC Container

The IoC container (ApplicationContext) is the heart of Spring. It creates objects (beans), wires them together, and manages their entire lifecycle.

Text
ApplicationContext (Spring IoC Container)
    │
    ├── Reads configuration (annotations, XML, Java config)
    │
    ├── Creates Beans (instances of classes with @Component, @Service, etc.)
    │
    ├── Injects Dependencies (using @Autowired)
    │
    ├── Manages Lifecycle (init, destroy, scopes)
    │
    └── Your Application Code uses ready-to-use beans

Spring Annotations for DI

Spring provides several annotations to mark classes as beans and to inject dependencies.

@Component (Generic Bean)

Java
@Component
public class UtilityHelper {
    // Spring will create an instance
}

@Service (Business Logic Layer)

Java
@Service
public class UserService {
    // Indicates this is a service layer bean
}

@Repository (Data Access Layer)

Java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    // Spring Data JPA creates implementation
}

@Controller / @RestController (Web Layer)

Java
@RestController
public class UserController {
    // Handles HTTP requests
}

@Autowired (Injection Point)

Java
@Service
public class OrderService {
    private final PaymentService paymentService;

    @Autowired // Optional when single constructor
    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}

Why Constructor Injection is Best

The Spring team recommends constructor injection for several reasons:

  • Immutability: Dependencies can be declared final
  • Null safety: Spring ensures dependencies are provided (no null beans)
  • Testability: Easy to create objects with mock dependencies in unit tests
  • Clear contract: Required dependencies are explicit in constructor signature
Java
// BEST: Constructor injection
@Service
public class UserService {
    private final UserRepository userRepository;
    private final EmailService emailService;

    public UserService(UserRepository userRepository, EmailService emailService) {
        this.userRepository = userRepository;
        this.emailService = emailService;
    }
}

// Unit test (easy!)
UserService service = new UserService(mockRepository, mockEmailService);
Avoid field injection (@Autowired on private fields). It makes testing difficult and hides dependencies. Constructor injection is the industry standard.

Qualifying Dependencies (@Qualifier)

When multiple beans of the same type exist, use @Qualifier to specify which one to inject.

Java
public interface PaymentProcessor { void process(); }

@Component
public class CreditCardProcessor implements PaymentProcessor { }

@Component
public class PayPalProcessor implements PaymentProcessor { }

@Service
public class CheckoutService {
    private final PaymentProcessor paymentProcessor;

    public CheckoutService(@Qualifier("creditCardProcessor") PaymentProcessor paymentProcessor) {
        this.paymentProcessor = paymentProcessor;
    }
}

Knowledge Check

Ready to test your understanding of 6. Dependency Injection & Inversion of Control?

Back