Java & Spring Boot Enterprise Mastery · Chapter 5 · ~15 min · Intermediate
Spring Boot 3 Core: The IoC Container & Dependency Injection
Demystify the engine powering enterprise Spring Boot 3 applications: Inversion of Control, the ApplicationContext dependency graph, constructor injection over fragile field injection, and the complete bean lifecycle from scanning to AOP proxying and destruction.
- Understand Inversion of Control and ApplicationContext container responsibilities
- Master constructor-based dependency injection over error-prone field injection
- Navigate Bean lifecycle phases from instantiation to @PostConstruct and @PreDestroy
- Configure conditional beans using @ConditionalOnProperty and @Configuration
Spring Boot 3 Core: The IoC Container & Dependency Injection: learn it visually
Demystify the engine powering enterprise Spring Boot 3 applications: Inversion of Control, the ApplicationContext dependency graph, constructor injection over fragile field injection, and the complete bean lifecycle from scanning to AOP proxying and destruction.
1Inversion of Control: The Dependency Injection Paradigm
In traditional programs, your code controls flow by directly instantiating dependencies with new ConcreteService(). In Inversion of Control (IoC), this control is inverted: an external container—the ApplicationContext—is responsible for discovering, instantiating, configuring, and assembling the dependency graph of your application.
@Component & Stereotypes
Spring scans annotations (@Service, @Repository, @RestController) and generates BeanDefinitions in memory.
Dependency Graph
The container resolves dependencies hierarchically. If Service A requires Repository B, B is instantiated first and passed to A.
Singleton vs Prototype
By default, Spring beans are singletons (one instance per ApplicationContext), ensuring memory efficiency and stateless thread safety.
// Modern Spring Boot 3 Constructor Injection (Zero @Autowired needed!)
@Service
public class PaymentProcessingService {
private final PaymentGatewayClient gatewayClient;
private final AuditLogRepository auditLogRepo;
private final MeterRegistry meterRegistry;
// Single public constructor: Spring Boot 3 automatically injects all parameters
public PaymentProcessingService(
PaymentGatewayClient gatewayClient,
AuditLogRepository auditLogRepo,
MeterRegistry meterRegistry
) {
this.gatewayClient = gatewayClient;
this.auditLogRepo = auditLogRepo;
this.meterRegistry = meterRegistry;
}
}Why does Spring engineering strongly discourage @Autowired on private fields in favor of constructor injection?
2Dual Mental Model: Manual Coupling vs Spring IoC Container
Compare the engineering realities of manually constructing object graphs versus delegating wiring to the Spring IoC container:
Wrong idea: Tight coupling via manual 'new' operators inside services
Instantiating concrete dependencies directly with new SqlDatabaseConnection(), hard-coding connection strings and making unit testing impossible.
Real system: Inversion of Control: container manages dependency graph
Declaring dependencies via interface contracts; the Spring ApplicationContext resolves, constructs, and injects singletons automatically at runtime.
3The Complete Spring Bean Lifecycle
A Spring bean undergoes a deterministic, multi-stage lifecycle orchestrated by the ApplicationContext. Understanding this sequence is vital for diagnosing injection order problems, circular dependencies, and AOP proxy behaviors:
@Component
public class CacheWarmupManager implements BeanNameAware {
private final RedisConnectionPool pool;
private String beanName;
public CacheWarmupManager(RedisConnectionPool pool) {
this.pool = pool; // 1. Construction & Dependency Injection
}
@Override
public void setBeanName(String name) {
this.beanName = name; // 2. Aware Interface Callback
}
@PostConstruct
public void init() {
// 3. Post-Construct Initialization: Dependencies & proxies are fully ready!
System.out.println("Bean [" + beanName + "] warming cache via pool...");
pool.prepopulateKeys();
}
@PreDestroy
public void cleanup() {
// 4. Graceful Shutdown: Invoked during SIGTERM or applicationContext.close()
System.out.println("Bean [" + beanName + "] flushing pending buffers...");
pool.flush();
}
}When is a method annotated with @PostConstruct executed during the bean lifecycle?
4Interactive Visualizer: Spring Bean Lifecycle & AOP Proxy
Step through each phase of bean instantiation, dependency resolution, AOP proxying, and destruction in the ApplicationContext:
Spring Bean Lifecycle & AOP Proxy Visualizer
Step through the exact phases executed by the ApplicationContext from component scan to destruction
Spring scans packages for @Component, @Service, and @Configuration classes, registering BeanDefinitions with metadata without instantiating objects yet.
BeanDefinitionRegistry.registerBeanDefinition("orderService", def);
ApplicationContext coordinates dependencies and proxies deterministically.
5Conditional Auto-Configuration (@ConditionalOnProperty)
In enterprise microservices, beans often need to be created conditionally depending on active environment profiles, feature flags, or classpath libraries:
@Configuration
public class NotificationAutoConfiguration {
@Bean
@ConditionalOnProperty(name = "notification.provider", havingValue = "aws-ses")
public NotificationClient sesClient(AwsConfig config) {
return new AwsSesNotificationClient(config);
}
@Bean
@ConditionalOnProperty(name = "notification.provider", havingValue = "sendgrid", matchIfMissing = true)
public NotificationClient sendGridClient(SendGridConfig config) {
return new SendGridNotificationClient(config);
}
}6Code Bug Hunt: Field Injection NPE in Unit Tests
The OrderService below relies on field injection with @Autowired. Refactor it to use clean, modern constructor injection with final fields so unit tests can inject mock dependencies directly without Spring:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
Refactor field injection to constructor injection:
- Remove the
@Autowiredannotations from the private fields. - Declare both dependencies as
private final OrderRepository orderRepository;andprivate final NotificationService notificationService;. - Add a public constructor:
public OrderService(OrderRepository orderRepository, NotificationService notificationService) { this.orderRepository = orderRepository; this.notificationService = notificationService; }.
7Chapter Knowledge Challenge
Test your mastery of Spring Boot 3 dependency injection and container architecture:
What is a circular dependency in Spring, and what happens in Spring Boot 3 if ServiceA requires ServiceB and ServiceB requires ServiceA via constructors?
What is the role of a BeanPostProcessor in the Spring Framework?
8Recap
- The ApplicationContext is the Spring IoC container responsible for instantiating, configuring, and assembling beans.
- Constructor injection with
finalfields is the enterprise standard, ensuring complete immutability and pain-free unit testing without launching Spring. - Startup logic must be placed inside
@PostConstructmethods rather than constructors so that dependencies and AOP proxies are fully active. - BeanPostProcessors wrap beans in AOP proxies after initialization to provide declarative transactions, caching, and security.
Ready for Chapter 6? Mark this chapter as complete to proceed: