IoC and Dependency Injection: how the Spring container works
Why a class that news up its dependencies can't be tested on its own; IoC, DI and ApplicationContext; creating and injecting beans, the lifecycle, scopes, proxies and self-invocation, circular dependencies; how to review Spring code written by AI.
On this page
1. The problem
Testing CheckoutService.checkout requires the whole Spring context, takes 40 seconds, and every run charges a real 10,000 VND on the Momo sandbox. The reason: the class does new MomoGateway() internally, so tests have no way to pass in a fake gateway. Adding VNPay means editing the same class again.
2. Key idea
A class that creates its own dependencies also owns the choice of implementation. Undo that by inverting the control: the class only declares what it needs (through the constructor, by interface), and something else assembles it. That something can be main (common in Go) or a container (Spring, ASP.NET Core, NestJS).
The container's cost: wiring errors move from compile time to startup, and proxies run behind the scenes.
| Choice | Use when | Don't use when |
|---|---|---|
| Constructor injection | the default for required dependencies | a long constructor: a signal to split the class |
ObjectProvider<T> |
optional, lazy, or fresh-every-time dependencies | required dependencies |
Field @Autowired |
test code, demos | production code: you can't new it in tests |
@Bean in @Configuration |
library classes, multi-step creation | a class already marked @Service: two beans |
@Lazy for cycles |
a temporary fix during an upgrade | instead of a redesign |
2.1 What goes wrong with scopes and proxies?
- A singleton (the default) is one instance per container, shared by every thread: a field holding per-request state is a race condition.
- A prototype injected into a singleton is created once, at injection; for a fresh one each time use
ObjectProvider.getObject(). - Proxies are created at the end of a bean's lifecycle (after
@PostConstruct) and only intercept calls from outside.this.save()inside the class bypasses the proxy, so@Transactionaldoes nothing.
3. In Java
The constructor takes an interface; a unit test calls new with a fake, no Spring needed.
interface PaymentGateway { PaymentResult pay(Order order); }
@Service
class CheckoutService {
private final PaymentGateway gateway;
CheckoutService(PaymentGateway gateway) { this.gateway = gateway; } // single constructor: no @Autowired needed
PaymentResult checkout(Order order) { return gateway.pay(order); }
}
@Configuration
class PaymentConfig {
@Bean
PaymentGateway momoGateway(HttpClient paymentHttpClient, MomoProperties props) {
return new MomoGateway(paymentHttpClient, props.endpoint(), props.secretKey());
}
}
// Unit test: no Spring, no network
var checkout = new CheckoutService(order -> PaymentResult.ok());
assertTrue(checkout.checkout(order).isSuccess()); // < 1 ms instead of 40 sOther languages: Go wires by hand in main or generates wiring code with Wire; C# has a built-in container in ASP.NET Core (builder.Services.AddScoped<...>()).
Component scanning, the bean lifecycle and dependency cycles
@SpringBootApplicationincludes@ComponentScan, which only scans the main class's package and subpackages: put the main class at the root package, or you'll get "No qualifying bean".ApplicationContextcreates every singleton at startup, so missing beans and cycles show up immediately (fail fast).- Lifecycle: read definitions → call the constructor → inject →
@PostConstruct→ wrap the proxy → ready →@PreDestroywhen the context closes. Calling a@Transactionalmethod from@PostConstructruns on the raw object, before the proxy exists. - A needs B and B needs A through constructors:
BeanCurrentlyInCreationExceptionat startup. Since Spring Boot 2.6, cycles are forbidden by default. It's almost always a split-responsibility problem: move the shared part to a third bean, or invert one direction with an event. - Only stateless, shared things are beans; DTOs and entities are per-request data.
4. Working with AI
Hand to AI: converting field injection to constructors, generating unit tests with new and fakes, reading startup logs to find cycles.
Check in AI-written code:
- No
@Autowiredon fields in production; dependencies areprivate final. - With
@RequiredArgsConstructor, every field to inject isfinal. - Singleton beans have no fields holding per-request state.
- No
this.x()calls to methods with@Transactional,@Async,@Cacheable. - Service unit tests use
new;@SpringBootTestis for integration tests only.
5. Exercises
Exercise 1: Review a "just switched to Lombok" refactor
The AI moved OrderService to @RequiredArgsConstructor and reported "context starts fine, tests green". A day later, POST /orders returns 500 on the first request. Find the bug, name a test that catches it, fix it.
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private PricingService pricingService;
public Order place(PlaceOrderRequest req) {
Money total = pricingService.total(req.items());
return orderRepository.save(Order.of(req, total));
}
}Solution to Exercise 1
pricingService isn't final, so Lombok leaves it out of the constructor and Spring never injects it. The context still starts because nothing demands that bean; a NullPointerException fires on the first call to place.
Test: a unit test new OrderService(repo, pricing) doesn't compile, because the generated constructor takes one parameter; add a test that calls POST /orders through the context. The AI's "green" tests probably mocked OrderService itself or never went through place.
Fix: private final PricingService pricingService;.
Exercise 2: Read a mixed-data incident
Two CSV import jobs run at once: file A has 1,000 rows, file B 800; the result is A's 1,000 rows plus 312 of B's mixed in. CsvParser is @Scope("prototype") and keeps parsed rows in a field; ImportService (a singleton) receives CsvParser through its constructor. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: a prototype injected into a singleton is fetched once, so both jobs share one
CsvParserand one row list: a race condition. - 15 minutes: run imports sequentially, then rerun file B.
- Root fix: inject
ObjectProvider<CsvParser>and callgetObject()per import, or makeCsvParserstateless: return the rows instead of keeping them in a field.
Summary
- IoC is the principle, DI the technique: a class declares what it needs, something else assembles it.
- Constructor injection by default; forgetting
finalwith@RequiredArgsConstructorleaves a fieldnull. - Singletons must be stateless; for a fresh prototype each time use
ObjectProvider. - Proxies only intercept outside calls;
this.method()loses@Transactional. - A dependency cycle is a responsibility problem: split a bean or use an event, don't reach for
@Lazy.
Read more: Reviewing AI-written code.
Practice interview questions on this topic
- What is the difference between IoC and Dependency Injection? What are a bean and the ApplicationContext?
- How do @Component, @Service, @Repository and @Bean differ? How is @Configuration different from @Component?
- Why prefer constructor injection? How does Spring handle circular dependencies?
- Two beans implement the same interface. How do you inject the one you want?
- What bean scopes does Spring have? Is a singleton bean thread-safe?
- What are the steps of a bean's lifecycle? How do BeanPostProcessor and BeanFactoryPostProcessor differ?
All Spring Boot questions →All Transactions & Locking questions →
Comments
Community rules