SteelReed

Search

Search posts, questions…

5. Spring Boot

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.

17 Nov 20269 min readMid

–

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 @Transactional does nothing.

3. In Java

The constructor takes an interface; a unit test calls new with a fake, no Spring needed.

JAVA
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 s

Other 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
  • @SpringBootApplication includes @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".
  • ApplicationContext creates 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 → @PreDestroy when the context closes. Calling a @Transactional method from @PostConstruct runs on the raw object, before the proxy exists.
  • A needs B and B needs A through constructors: BeanCurrentlyInCreationException at 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 @Autowired on fields in production; dependencies are private final.
  • With @RequiredArgsConstructor, every field to inject is final.
  • Singleton beans have no fields holding per-request state.
  • No this.x() calls to methods with @Transactional, @Async, @Cacheable.
  • Service unit tests use new; @SpringBootTest is 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.

JAVA
@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 CsvParser and one row list: a race condition.
  • 15 minutes: run imports sequentially, then rerun file B.
  • Root fix: inject ObjectProvider<CsvParser> and call getObject() per import, or make CsvParser stateless: 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 final with @RequiredArgsConstructor leaves a field null.
  • 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

All Spring Boot questions →All Transactions & Locking questions →

Loading comments…
Next on the roadmapSpring AOP and BeanPostProcessor: proxies, pointcuts and advice order