Skip to content
Veltoryx Technologies
FreeLesson 1.2Beginner5 min readUpdated 31 October 2026

Inversion of Control & Dependency Injection: The Restaurant Kitchen

Master Inversion of Control and Dependency Injection through simple analogies, constructor injection best practices, and stereotype annotations.

01The problem with manual object creation

In traditional object-oriented programming, whenever a class needs a helper, it uses the new keyword:

java
public class OrderService {
    // Tight coupling! OrderService controls how and when SqlDatabase is built
    private SqlDatabase db = new SqlDatabase("db.prod.company:5432");
}

This creates severe architectural headaches:

  • Zero testability: How can you test OrderService without actually connecting to a production PostgreSQL database? You can't, because new SqlDatabase(...) is hard-coded inside.
  • Cascading changes: If SqlDatabase later requires a connection timeout parameter in its constructor, every single class that wrote new SqlDatabase() breaks.
  • Tight coupling: OrderService is permanently welded to one concrete database implementation.

02The solution: Inversion of Control (IoC)

Think about staying at a hotel.

  • Traditional approach: You buy a stove, pan, and groceries, drag them up to your room, and cook your own dinner. You control every detail, but it's exhausting.
  • Inversion of Control (IoC): You pick up the phone, dial room service, and say: "I need dinner." The kitchen handles cooking, plating, and delivery. Control has been inverted. You no longer manage how dinner is made; the hotel does.

In Spring, the IoC Container (specifically the ApplicationContext) is that hotel kitchen. It instantiates objects, configures them, wires them together, and delivers them to your classes when needed.

Inversion of Control: The Restaurant Kitchen Analogy
Fig. 1 · Inversion of Control: The Restaurant Kitchen Analogy

03What is a Spring Bean?

A Bean sounds fancy, but in plain English:

A Spring Bean is simply a normal Java object whose creation, lifecycle, and destruction are managed by the Spring IoC Container.

If you write OrderService service = new OrderService();, it is a regular Java object. If Spring creates it and stores it in its container, it is a Spring Bean.

04Stereotype annotations: giving Beans their roles

To tell Spring to manage a class, you attach a stereotype annotation above the class definition:

AnnotationAnalogyRole in Application
@ComponentGeneral workerGeneric Spring-managed bean for any utility or helper.
@ServiceThe Executive ChefHouses core business logic, validations, and domain rules.
@RepositoryThe Pantry KeeperEncapsulates database operations and translates SQL exceptions into Spring's unified DataAccessException.
@Controller / @RestControllerThe WaiterHandles incoming HTTP requests, unpacks JSON, and formats responses.

All of these are specializations of @Component. Under the hood, Spring treats them all as beans, but using the specific stereotype makes your architectural layers crystal clear.

05The three ways to inject dependencies

How does a bean receive its collaborators?

1. Field Injection (The Anti-Pattern ⚠️)

java
@Service
public class OrderService {
    @Autowired
    private PaymentGateway paymentGateway; // Don't do this!
}

Why is this discouraged?

  • You cannot write clean unit tests without reflection or starting a full Spring context.
  • Fields cannot be marked final, meaning the object can be mutated accidentally.
  • It hides circular dependencies until runtime.

2. Setter Injection (Optional dependencies)

java
@Service
public class OrderService {
    private PaymentGateway paymentGateway;

    @Autowired
    public void setPaymentGateway(PaymentGateway gateway) {
        this.paymentGateway = gateway;
    }
}

Useful only if a dependency is truly optional and has a sensible default.

3. Constructor Injection (The Modern Industry Standard ✅)

java
@Service
public class OrderService {
    private final PaymentGateway paymentGateway;
    private final NotificationService notifications;

    // In modern Spring (4.3+ and Boot 3), @Autowired on constructors is optional!
    public OrderService(PaymentGateway paymentGateway, NotificationService notifications) {
        this.paymentGateway = paymentGateway;
        this.notifications = notifications;
    }
}

Benefits of Constructor Injection:

  • Immutability: Dependencies are marked final. Once created, the bean cannot be altered.
  • Easy Unit Testing: In your JUnit tests, you can write new OrderService(mockGateway, mockNotifications) without needing Spring at all.
  • Fail-Fast: If a required bean is missing, the application crashes immediately on startup rather than failing at 3 AM when a request hits a null pointer.

06Complete working example

java
package com.veltoryx.demo.order;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;

// 1. Data Access Layer
@Repository
public class OrderRepository {
    public boolean save(String item, int amount) {
        // Pretend this writes to PostgreSQL
        return true;
    }
}

// 2. Business Logic Layer
@Service
public class OrderService {
    private final OrderRepository repository;

    public OrderService(OrderRepository repository) {
        this.repository = repository;
    }

    public String processOrder(String item, int quantity) {
        if (quantity <= 0) throw new IllegalArgumentException("Quantity must be positive");
        boolean success = repository.save(item, quantity);
        return success ? UUID.randomUUID().toString() : null;
    }
}

// 3. Web Presentation Layer
@RestController
@RequestMapping("/api/orders")
public class OrderController {
    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    public record OrderRequest(String item, int quantity) {}
    public record OrderResponse(String orderId, String status) {}

    @PostMapping
    public OrderResponse create(@RequestBody OrderRequest req) {
        String id = orderService.processOrder(req.item(), req.quantity());
        return new OrderResponse(id, "CONFIRMED");
    }
}

Notice how clean the wiring is: OrderController asks for OrderService, which asks for OrderRepository. Spring automatically discovers all three, creates them in reverse dependency order, and injects them without a single line of manual wiring.

07Common mistakes and traps

  • Circular Dependencies: Bean A requires Bean B in its constructor, and Bean B requires Bean A. Spring Boot 3 will throw a BeanCurrentlyInCreationException and immediately refuse to start. Fix this by rethinking your design or using domain events.
  • Using @Autowired on private fields in new code: It makes unit tests tedious and hides object dependencies. Always use constructor injection.

08In the interview

Common follow-up questions:

  • What is the difference between @Component and @Bean? @Component is placed at the class level for auto-detection via component scanning on classes you own. @Bean is a method-level annotation placed inside @Configuration classes, used when you need to configure and return third-party library classes you don't own (like a custom ObjectMapper or Redis template).
  • Does modern Spring require @Autowired on constructors? No. Since Spring 4.3 and in all Spring Boot versions, if a class has only one constructor, Spring automatically treats it as @Autowired.

09Check your understanding

Quiz · 4 questions

0 of 4 answered

  1. 1. What is the primary difference between a normal Java object and a Spring Bean?

  2. 2. Why is constructor injection preferred over field injection with @Autowired?

  3. 3. When should you use @Bean instead of @Component?

  4. 4. What happens if Bean A and Bean B require each other in their constructors (circular dependency) in Spring Boot 3?