Chapter 5 of 12
Course Progress0 of 12 completed (0%)

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.

Spring Boot 3 Core: The IoC Container & Dependency InjectionDemystify 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.UNDERSTANDSpring Boot CoreFOLLOW THE FLOWCALLIoC ContainerAPPLY ITDependency InjectionSpring Boot 3 Core: The IoC Container & Dependency InjectionDemystify 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.UNDERSTANDSpring Boot CoreFOLLOW THE FLOWCALLIoC ContainerAPPLY ITDependency Injection

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.

Discovery

@Component & Stereotypes

Spring scans annotations (@Service, @Repository, @RestController) and generates BeanDefinitions in memory.

Resolution

Dependency Graph

The container resolves dependencies hierarchically. If Service A requires Repository B, B is instantiated first and passed to A.

Scope Management

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;
    }
}
Concept Check

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

class Service { private Repo repo = new PostgresRepo("localhost"); }Rigid coupling · impossible to mock in isolation · test brittle

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

public Service(PaymentRepo repo) { this.repo = repo; }Decoupled contracts · 100% testable with mock injection · configurable

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();
    }
}
Concept Check

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

1. Component Scanning & BeanDefinition
CONFIGURATION

Spring scans packages for @Component, @Service, and @Configuration classes, registering BeanDefinitions with metadata without instantiating objects yet.

Internal Bean State:Uninstantiated (Metadata only)
Spring Internal Hook Action
ApplicationContext

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:

Refactor @Autowired Field Injection to Constructor Injection
Java

🎯 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 @Autowired annotations from the private fields.
  • Declare both dependencies as private final OrderRepository orderRepository; and private 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:

Concept Check 1 of 2
1

What is a circular dependency in Spring, and what happens in Spring Boot 3 if ServiceA requires ServiceB and ServiceB requires ServiceA via constructors?

Concept Check 2 of 2
2

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 final fields is the enterprise standard, ensuring complete immutability and pain-free unit testing without launching Spring.
  • Startup logic must be placed inside @PostConstruct methods 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:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us