Skip to content
notes.vinhnq.com

Search

SpringMid21 min read

IoC and Dependency Injection: how the Spring container works

Review 28 cards
On this page

A class that news up everything it needs is welded to those classes: switching implementations means editing code, and unit testing drags in a real database. IoC and DI cut those ties: the class only declares what it needs, and Spring’s IoC container (ApplicationContext) creates and assembles it. By the end you’ll be able to explain how the container creates, injects and manages beans, and how lifecycles, scopes, proxies and circular dependencies work.

1. Coupling: the root problem

Key idea: coupling is how strongly two modules depend on each other. A class that depends on an interface and receives its dependencies from outside is easy to swap and test; a class that news a concrete class isn’t.

  • Tight coupling: A knows B’s concrete class and creates B itself.
  • Loose coupling: A only knows an interface of B and doesn’t care who creates it.

Tight coupling

class MomoGateway {
    PaymentResult pay(Order order) { /* call the Momo API */ }
}

class CheckoutService {
    private final MomoGateway gateway = new MomoGateway();   // creates it itself, hard-wired to Momo

    PaymentResult checkout(Order order) {
        return gateway.pay(order);
    }
}

Want to add VNPay? Edit CheckoutService. Want to test checkout without calling the real Momo API? Good luck.

Loose coupling through an interface and a constructor

interface PaymentGateway {
    PaymentResult pay(Order order);
}

class MomoGateway implements PaymentGateway { ... }
class VnPayGateway implements PaymentGateway { ... }

class CheckoutService {
    private final PaymentGateway gateway;

    CheckoutService(PaymentGateway gateway) {   // handed in from outside
        this.gateway = gateway;
    }
}

Thanks to polymorphism, any implementation works. This is the Dependency Inversion Principle (the D in SOLID): high-level and low-level modules both depend on abstractions.

But who does the assembly?

PaymentGateway momo = new MomoGateway(httpClient, momoConfig);
PaymentGateway vnpay = new VnPayGateway(httpClient, vnpayConfig);
CheckoutService checkout = new CheckoutService(momo);
RefundService refund = new RefundService(vnpay, orderRepository);   // oops, wrong one?

With hundreds of classes, wiring by hand causes three problems: you manage creation order and lifecycle yourself (when do you close the connection pool?), it’s easy to pass the wrong object, and cycles appear (A needs B, B needs A, which comes first?).

2. Inversion of Control

Key idea: IoC inverts who’s in charge: the framework creates the objects, connects them and calls your code when needed (“Don’t call us, we’ll call you”).

  • Traditional: you need a motorbike, so you buy an engine, a frame and wheels and assemble it yourself, knowing every part and the order they go in.
  • IoC: you just say “I need a motorbike”, and a factory (the IoC container) builds it and delivers it to your door. The delivery is dependency injection; the bike is the dependency.
flowchart LR
  subgraph T[Traditional]
    direction LR
    A1[My code] -- buys and assembles every part --> P1[Engine, Frame, Wheel]
    P1 --> O1[Object I need]
  end
  subgraph I[IoC]
    direction LR
    A2[My code] -- declares: I need a motorbike --> F[IoC container]
    F -- injects the assembled dependency --> A2
  end

Besides DI, IoC also comes as the template method (the framework calls your hook methods), callbacks/event listeners, and the service locator (you ask a registry for a dependency). Spring uses DI, the most common form.

3. Dependency Injection and the IoC container

Key idea: DI means handing dependencies to an object instead of letting it create or look them up. In Spring the container is the ApplicationContext, and the objects it manages are beans.

  • Bean: an object the container creates and manages, usually a controller, service, repository, configuration or client.
  • When bean A needs bean B, the container looks B up in the context: if it doesn’t exist yet it creates it, otherwise it reuses it, and injects it into A.
  • ApplicationContext belongs to the Spring Framework, not just Spring Boot. Boot only auto-configures and creates the context for you.

BeanFactory vs ApplicationContext

ApplicationContext extends BeanFactory and creates every singleton up front at startup. So configuration mistakes (missing beans, dependency cycles) blow up at startup rather than on the first request: a deliberate fail fast.

BeanFactory vs ApplicationContext comparison table
BeanFactory ApplicationContext
Role The root interface; just creates and returns beans Extends BeanFactory
Singleton creation Lazy (on request) Eager at startup (by default)
Extras Events, i18n (MessageSource), Environment/profiles, automatic BeanPostProcessor registration, resource loading
When used Almost never directly Every Spring app

Component scanning

4. Creating beans

Key idea: annotate your own classes with a stereotype (@Service…); for library classes or beans that take several steps to build, declare a @Bean method in a @Configuration class.

Option 1: stereotype annotations

@Service
public class CheckoutService { ... }
Annotation Used for Real difference
@Component Generic bean The root of all stereotypes
@Service Business layer Just a name that helps readability
@Repository Data access layer Turns on exception translation from JDBC/JPA into Spring’s DataAccessException
@Controller / @RestController Web layer Picked up by DispatcherServlet to map requests
@Configuration Class that defines beans Gets a CGLIB proxy (see below)

Option 2: @Configuration + @Bean

@Configuration
public class PaymentConfig {

    @Bean
    public HttpClient paymentHttpClient() {
        return HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(3))
                .build();
    }

    @Bean
    public PaymentGateway momoGateway(HttpClient paymentHttpClient, MomoProperties props) {
        return new MomoGateway(paymentHttpClient, props.endpoint(), props.secretKey());
    }
}

The parameters of a @Bean method are injected too. The bean name defaults to the method name.

5. Injecting beans into other beans

Key idea: there are three ways to inject: field, constructor and setter. Constructor injection is the default; setters are for optional dependencies; avoid field injection in production code.

Field injection

@Service
public class ReportService {
    @Autowired
    private OrderRepository orderRepository;
}

Constructor injection

@Service
public class ReportService {
    private final OrderRepository orderRepository;

    public ReportService(OrderRepository orderRepository) {   // no @Autowired needed
        this.orderRepository = orderRepository;
    }
}

Setter injection

@Service
public class ReportService {
    private ReportExporter exporter;

    @Autowired
    public void setExporter(ReportExporter exporter) {
        this.exporter = exporter;
    }
}

Comparison

Several beans of the same type

Adapter and Factory uses option 3 to build a Map<ListingType, BookingHandler> registry with duplicate/missing checks at startup.

What else the Adapter and Factory post covers

It builds the registry from a List<BookingHandler>, compares it with a switch-based simple factory, and reproduces both the @RequiredArgsConstructor trap and the trap of injecting by a parent class whose subclasses are also beans. It also retells the course’s two analogies (the boss and the pizza maker, the bicycle factory) to tell Dependency Inversion, IoC and DI apart.

For optional dependencies: Optional<T>, @Autowired(required = false), or ObjectProvider<T> (lazy, with getIfAvailable()).

6. The bean lifecycle

Key idea: the container reads the bean definition, calls the constructor, injects, runs the init callbacks (@PostConstruct), and only then wraps the AOP proxy; when the context closes it calls @PreDestroy.

flowchart TD
  A[Read BeanDefinition<br/>scan / @Bean] --> B[BeanFactoryPostProcessor<br/>edits definitions, e.g. resolves placeholders]
  B --> C[Instantiate: call the constructor]
  C --> D[Populate: inject fields/setters]
  D --> E[Aware callbacks<br/>BeanNameAware, ApplicationContextAware]
  E --> F[BeanPostProcessor.before<br/>@PostConstruct runs here]
  F --> G[InitializingBean.afterPropertiesSet<br/>then init-method]
  G --> H[BeanPostProcessor.after<br/>the AOP proxy is created here]
  H --> I[Bean ready to use]
  I --> J[Context closes: @PreDestroy<br/>DisposableBean.destroy, destroy-method]
  • BeanFactoryPostProcessor edits bean definitions before creation. BeanPostProcessor works on instances after creation. Most of Spring’s “magic” (@Autowired, @Async, @Transactional, @Scheduled) runs on these post processors.
  • Prototype beans get no destroy callback: the container hands them over and stops managing them.

7. Bean scopes

Key idea: the scope decides how many instances of a bean the container creates. The default is singleton: one instance per container, shared by every thread.

Scope Instances Notes
singleton (default) One per bean definition per container Not a JVM-wide singleton like the design pattern
prototype A new one on every lookup/injection No destroy callback
request One per HTTP request Web apps only
session One per HTTP session
application One per ServletContext
websocket One per WebSocket session

Singletons must be thread-safe

Injecting a prototype into a singleton

8. Proxies: the key to AOP in Spring

Key idea: for @Transactional, @Async, @Cacheable, @Validated and @PreAuthorize, Spring injects a proxy that wraps your bean. The proxy intercepts the call, does the extra work (opens a transaction, hands off to another thread…) and then calls the real object; a call that doesn’t go through the proxy gets none of that.

A proxy is like a secretary outside the director’s office: visitors who go through the secretary get logged, but the director talking to himself doesn’t.

sequenceDiagram
  participant C as OrderController
  participant P as OrderService proxy
  participant T as OrderService (real object)
  C->>P: placeOrder()
  P->>P: open transaction
  P->>T: placeOrder()
  T->>T: this.sendEmail() internal call, does NOT go through the proxy
  T-->>P: return
  P->>P: commit / rollback
  P-->>C: return
JDK dynamic proxies vs CGLIB proxies
JDK dynamic proxy CGLIB proxy
Mechanism Implements the same interface Generates a subclass at runtime
Requires The bean has an interface Non-final class, non-final/non-private methods
Default in Plain Spring Framework when there’s an interface Spring Boot (spring.aop.proxy-target-class=true)

The bean’s runtime type is OrderService$$SpringCGLIB$$0, not OrderService, so getClass() comparisons go wrong.

9. Circular dependencies

Key idea: if A needs B and B needs A through their constructors, Spring can’t create either first and throws BeanCurrentlyInCreationException at startup. A cycle almost always means responsibilities are split wrongly.

@Service
class OrderService {
    OrderService(InventoryService inventory) { ... }
}

@Service
class InventoryService {
    InventoryService(OrderService orders) { ... }
}
The three-level singleton cache: how Spring used to “rescue” field injection

10. The layers of a Spring Boot project

Key idea: only stateless, shared things are beans (controllers, services, repositories). DTOs and entities are data created per request, so they aren’t beans.

Layer Responsibility Bean?
Controller Receives requests, maps endpoints, calls services @RestController
DTO Carries data between layers, hides sensitive entity fields No, a plain object
Service Business logic, transactions @Service
Repository Queries and data operations @Repository / Spring Data interface
Entity Maps to a database table No, managed by JPA

Dependency direction between layers (controllers don’t call repositories directly, the domain doesn’t depend on the web layer) is best enforced with ArchUnit tests, not by eyeballing code reviews.

Dependency Injection is not Dependency Inversion

  • Dependency Injection is a technique: who creates objects and hands them their dependencies (here, Spring, through the constructor).
  • Dependency Inversion (the D in SOLID) is a principle: business logic doesn’t depend on infrastructure; both depend on an abstraction, and the abstraction belongs to the business side.

You can use DI and still break DIP: a service that receives a concrete JpaOrderRepository, or imports JPA entities and JpaRepository, is still tied to infrastructure. Applying DIP: put an OrderRepository interface next to the domain and let a JPA adapter implement it. How to structure a codebase around this principle is covered in Codebase architecture: layered, hexagonal, onion, clean.

Exercises

Exercise 1: Move logic from controllers into services

The task (paraphrased): define service classes for the pet project and move all business logic that currently lives in controllers into the service layer.

Solution to exercise 1
// Before: the controller does everything
@RestController
@RequestMapping("/api/products")
class ProductController {
    @Autowired ProductRepository repo;

    @PostMapping
    Product create(@RequestBody ProductRequest req) {
        if (repo.existsBySku(req.sku())) throw new IllegalStateException("sku exists");
        Product p = new Product(req.sku(), req.name(), req.price());
        return repo.save(p);
    }
}

// After: the controller is just an HTTP transport layer
@RestController
@RequestMapping("/api/products")
class ProductController {
    private final ProductService productService;

    ProductController(ProductService productService) {
        this.productService = productService;
    }

    @PostMapping
    ResponseEntity<ProductResponse> create(@Valid @RequestBody ProductRequest req) {
        ProductResponse created = productService.create(req);
        return ResponseEntity.created(URI.create("/api/products/" + created.id())).body(created);
    }
}

@Service
class ProductService {
    private final ProductRepository repo;

    ProductService(ProductRepository repo) {
        this.repo = repo;
    }

    @Transactional
    public ProductResponse create(ProductRequest req) {
        if (repo.existsBySku(req.sku())) {
            throw new BusinessException(ErrorCode.PRODUCT_SKU_TAKEN);
        }
        return ProductResponse.from(repo.save(Product.from(req)));
    }
}

The rule: controllers handle HTTP (status, headers, DTO mapping), services handle business logic and transactions. No HttpServletRequest or ResponseEntity in a service.

Exercise 2: Create service beans two ways

The task (paraphrased): register service beans with annotations, and with @Configuration + @Bean.

Solution to exercise 2
// Option 1: annotation
@Service
public class ProductService { ... }

// Option 2: no @Service on the class, declare it in a config
public class CategoryService {
    private final CategoryRepository repo;
    public CategoryService(CategoryRepository repo) { this.repo = repo; }
}

@Configuration
public class ServiceConfig {
    @Bean
    public CategoryService categoryService(CategoryRepository repo) {
        return new CategoryService(repo);
    }
}

Exercise 3: Inject three ways

The task (paraphrased): inject the service beans using field, constructor and setter injection. Then write a unit test for each controller without Spring (plain new with mocks).

Solution to exercise 3
@RestController
class CategoryController {
    @Autowired
    private CategoryService categoryService;                 // field
}

@RestController
class ProductController {
    private final ProductService productService;             // constructor (recommended)
    ProductController(ProductService productService) { this.productService = productService; }
}

@RestController
class ReportController {
    private ReportService reportService;

    @Autowired
    void setReportService(ReportService reportService) {     // setter
        this.reportService = reportService;
    }
}

Writing the tests makes it obvious: constructor injection is the easiest to test, while field injection forces you into @InjectMocks or reflection. Writing those unit tests with JUnit 5 and Mockito: unit testing with JUnit 5 and Mockito.

Exercise 4: Validate request data in the service

The task (paraphrased): write code that validates incoming request data in the service layer.

Solution to exercise 4

Split the roles: DTOs plus Bean Validation check the shape of the input (not blank, right format) in the controller; the service checks business rules that need other data (existence, state, relationships).

@Service
@Validated                                       // turns on method validation for the service
class OrderService {

    @Transactional
    public OrderResponse place(@Valid PlaceOrderRequest req) {   // still runs when called from outside a controller
        Product product = productRepo.findById(req.productId())
                .orElseThrow(() -> new BusinessException(ErrorCode.PRODUCT_NOT_FOUND));
        if (!product.isActive()) {
            throw new BusinessException(ErrorCode.PRODUCT_INACTIVE);
        }
        if (product.stock() < req.quantity()) {
            throw new BusinessException(ErrorCode.OUT_OF_STOCK);
        }
        ...
    }
}

Since @Validated relies on a proxy, calling place from inside OrderService itself (this.place(...)) won’t validate. For how to design BusinessException and handle errors centrally, see Exceptions in Java.

Remember

  • Can you tell IoC, DI and Dependency Inversion apart in one sentence each?
  • Can you explain why constructor injection is the default, and the forgotten-final trap with @RequiredArgsConstructor?
  • Do you know at which lifecycle step the proxy is created, and why self-invocation or @PostConstruct loses @Transactional?
  • Do you know when a singleton causes a race condition, and how to get a fresh prototype from a singleton each time?
  • Can you list the fixes for a circular dependency in order: redesign, events, @Lazy, re-enable the setting?

Interview questions

Junior

What’s the difference between IoC and DI?

IoC is the principle (the framework owns creating and wiring objects); DI is one way to implement it.

With DI, dependencies are handed to an object through its constructor, setters or fields instead of the object creating them. Other ways to implement IoC: template methods, callbacks, the service locator.

What is a bean? What is the ApplicationContext?

A bean is an object whose creation and lifecycle the Spring IoC container manages; the ApplicationContext is that container.

It extends BeanFactory with events, i18n, environment/profiles and eager singleton creation at startup.

How do @Component, @Service and @Repository differ?

All three mark a class as a bean for component scanning; only @Repository adds behavior.

@Service differs only in meaning. @Repository translates persistence-layer exceptions into DataAccessException.

Why prefer constructor injection?

Because required dependencies are guaranteed the moment the object exists, and the class is testable without Spring.

On top of that: fields can be final, a long constructor warns that the class does too much, and dependency cycles show up at startup.

Mid

When would you use @Bean instead of @Component?

When you can’t edit the class’s source (a third-party library).

Or when creating the bean needs non-trivial logic or configuration parameters, or when you want several beans of one type with different configurations.

Two beans implement the same interface. How do you inject one?

@Primary for the default bean, @Qualifier("name") to ask for a specific one.

Or inject a List<T>/Map<String, T> to get all of them, which suits the strategy pattern.

Are singleton beans thread-safe?

No, Spring doesn’t make them thread-safe; the bean has to be stateless.

One instance is shared across threads. Per-request state goes through parameters, or into request scope / a ThreadLocal that gets cleaned up.

Walk through the main steps of a bean’s lifecycle.

Read the definition, create, inject, initialise, wrap in a proxy, use, destroy.

In detail: read the definition, run BeanFactoryPostProcessors, call the constructor, inject dependencies, Aware callbacks, BeanPostProcessor.before (including @PostConstruct), afterPropertiesSet/init-method, BeanPostProcessor.after (creates the AOP proxy), use, then @PreDestroy/destroy when the context closes. Prototypes get no destroy callback.

Senior

Why doesn’t @Transactional work when you call a method in the same class?

Because transactions are applied by a proxy around the bean, and this.method() calls the real object directly.

Fixes: move the method to another bean, or use TransactionTemplate. The same goes for @Async, @Cacheable, and for private/final methods under CGLIB.

How does Spring deal with circular dependencies?

With constructor injection it can’t (BeanCurrentlyInCreationException); the real fix is redesign.

With field/setter injection, the three-level singleton cache allows injecting an early reference, but since Boot 2.6 that’s banned by default. Fix it by extracting a third bean or using events; @Lazy is only a stopgap.

What happens if you inject a prototype bean into a singleton?

The prototype is fetched once when the singleton is created, so it’s always the same instance.

Use ObjectProvider<T>.getObject(), @Lookup or a scoped proxy to get a new instance each time.

How is @Configuration different from a @Component with @Bean methods?

@Configuration (full mode) gets a CGLIB proxy, so calling one @Bean method from another still returns the same singleton.

In a @Component or with proxyBeanMethods = false (lite mode), that call creates a new object. Lite mode starts faster, but you must take dependencies as method parameters.

How does DI help with testing and long-term architecture?

Testing: swap dependencies for mocks or fakes without a container or real infrastructure. Architecture: code depends on abstractions, so implementations change through configuration.

You can swap the database, payment provider or cache without touching business logic; combine it with automated architecture checks (ArchUnit) to keep layer boundaries intact.

Useful phrases for interviews

  • “Inversion of control means the framework owns object creation and wiring, and dependency injection is how Spring delivers those objects to my classes.”
  • “I default to constructor injection because it makes dependencies explicit, keeps fields final and makes unit tests trivial.”
  • “Singleton beans are shared across threads, so I keep them stateless.”
  • “Annotations like @Transactional work through proxies, which is why self-invocation silently bypasses them.”
  • “If I hit a circular dependency, I treat it as a design smell and extract the shared logic rather than reaching for @Lazy.”
  • “I’d use a @Bean method when I need to configure a third-party class that I can’t annotate.”
  • “When there are multiple implementations, I inject them as a map and pick one at runtime, which is basically the strategy pattern.”
  • “Because the context creates singletons eagerly, wiring mistakes fail fast at startup rather than in production traffic.”

Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words.