Lecture 26: Spring IoC & Bean Life Cycle

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-10

Lecture 26

Spring IoC & Bean Life Cycle

Week 7 | Unit IV: Spring Framework Basics
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Define Spring IoC and bean lifecycle in clear terms
  • Explain what the IoC container does in practice
  • Summarize the evolution of IoC in Spring
  • List key advantages of IoC-based lifecycle management
  • Explain IoC container responsibilities
  • Understand bean lifecycle stages
  • Use lifecycle callbacks correctly

Prerequisites


  • Core Java OOP concepts and interface-based design
  • Basic understanding of Servlets/JSP request flow from Unit III
  • Revision of Lecture 25 before moving into Spring IoC & Bean Life Cycle

Syllabus Mapping


  • Unit IV topic focus: Spring IoC & Bean Life Cycle
  • CO alignment: implementation understanding + architecture reasoning
  • Assessment alignment: short definitions + long implementation/design questions

Agenda


  • 5-minute recap from previous lecture
  • Concept deep dive: Spring IoC & Bean Life Cycle
  • Code/configuration walkthrough and output analysis
  • Debug checklist and exam-oriented summary

Introduction


Spring IoC is not only about creating objects. It defines a complete lifecycle for beans:

  • bean creation and dependency resolution
  • initialization callbacks before business use
  • controlled shutdown and resource cleanup

Lifecycle control becomes critical in enterprise systems where services open files, database connections, messaging clients, and thread pools.

Definition of Spring IoC


Inversion of Control (IoC) is a design principle where object creation, dependency wiring, and lifecycle handling are managed by a container, instead of being hardcoded inside application classes.

In Spring, this container is the ApplicationContext.

What the IoC Container Is


The IoC container is the runtime engine that:

  • reads configuration or component scans
  • creates beans and injects dependencies
  • applies lifecycle callbacks at startup and shutdown
  • provides ready-to-use objects to business code

In one line: business classes focus on logic, container handles lifecycle mechanics.

History of IoC in Spring


Quick evolution:

  • 2003-2004: Spring popularizes lightweight IoC and DI in enterprise Java
  • Early versions: XML-based bean configuration dominates
  • Later versions: annotation-driven configuration becomes mainstream
  • Spring Boot era: convention-based setup makes IoC adoption faster and cleaner

Advantages of IoC and Lifecycle Control


Why this matters in real systems:

  • Loose coupling: classes depend on abstractions, not concrete creation code
  • Predictable startup: init callbacks run in a controlled order
  • Safe shutdown: destroy callbacks reduce resource leaks
  • Better testing: dependencies are easy to replace with test doubles
  • Cleaner architecture: lifecycle concerns stay out of business methods

Think About It


Key lifecycle design questions:

  1. Which tasks belong in construction and which belong in initialization callbacks?
  2. What risks appear when cleanup logic is missing at shutdown?
  3. How does lifecycle management improve reliability in long-running applications?

Why Bean Lifecycle Management Matters


Without lifecycle discipline, enterprise applications face:

  • repeated heavy initialization on each request
  • resource leaks from unclosed connections/files
  • startup timing issues caused by incorrect dependency order
  • unpredictable behavior during application shutdown

Lifecycle callbacks provide deterministic startup and cleanup behavior.

Bean Lifecycle Stages in Spring


Lifecycle stages in order:

  1. Bean instantiation
  2. Dependency injection
  3. BeanNameAware, BeanFactoryAware, etc. (if implemented)
  4. BeanPostProcessor before-initialization
  5. @PostConstruct / afterPropertiesSet() / custom initMethod
  6. Bean is ready for business use
  7. @PreDestroy / DisposableBean / custom destroyMethod

Bean Lifecycle


flowchart LR
    A["Instantiate Bean"] --> B["Dependency Injection"]
    B --> C["@PostConstruct / init-method"]
    C --> D["Bean in Use"]
    D --> E["@PreDestroy / destroy-method"]

  • IoC container controls complete object lifecycle
  • Initialization hooks are ideal for setup logic
  • Destruction hooks release resources cleanly

Lifecycle Callback Options


Approach Init Destroy Typical Use
JSR-250 @PostConstruct @PreDestroy Clean, annotation-based lifecycle hooks
Spring Interfaces InitializingBean DisposableBean Framework-specific explicit callbacks
Java Config initMethod destroyMethod Externalized lifecycle in configuration

For most projects, @PostConstruct and @PreDestroy provide readable lifecycle logic.

Code Walkthrough


@PostConstruct
public void init(){ System.out.println("bean ready"); }

@PreDestroy
public void close(){ System.out.println("bean destroyed"); }

@Bean(initMethod = "init", destroyMethod = "close")
public ReportService reportService() {
    return new ReportService();
}

Walkthrough checkpoints:

  • callback sequence should appear in startup/shutdown logs
  • init logic must avoid business processing side effects
  • destroy logic should release external resources safely

Important Caveat: Prototype Bean Destruction


In Spring, @PreDestroy is not automatically called for prototype beans because the container does not fully manage their complete lifecycle after creation.

Implication: - for prototype beans using external resources, application code must handle cleanup.

@Scope("prototype")
class TempWorker {
    @PreDestroy
    void close() { /* may not be called automatically */ }
}

Testing Lifecycle Behavior


Lifecycle behavior should be verified explicitly:

  • assert init callbacks executed after dependency injection
  • assert destroy callbacks execute on context close
  • verify no resource leaks in repeated start/stop cycles
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
ctx.getBean(ReportService.class);
ctx.close(); // expect destroy callback

Recap points:

  • lifecycle callbacks execute around bean usage, not in business method flow
  • container-managed lifecycle improves reliability and startup/shutdown discipline
  • lifecycle behavior must be verified in both runtime logs and tests

Live Demo


Live implementation for Spring IoC & Bean Life Cycle:

Open Demo: Lecture 26 - Spring IoC & Bean Life Cycle

Demo checklist: - Start app and inspect bean creation plus init order in logs - Trigger a request and show bean usage phase - Stop context/application and verify destroy callback execution - Simulate missing callback annotation and diagnose behavior

Resources & References


Structured Debug Checklist


  1. verify the primary API usage for Spring IoC & Bean Life Cycle is correct (imports, method names, config)
  2. check request/bean/session flow and object lifecycle assumptions
  3. inspect server logs for the first exception (not just the final symptom)
  4. reproduce one failing case and one passing case before finalizing fixes

Exam Preparation Questions: Short


  • Define Spring IoC & Bean Life Cycle with one practical use case.
  • Write/identify the key API or construct: bean instantiation and lifecycle callbacks.
  • Differentiate: Manual object creation vs IoC-managed bean lifecycle.
  • Mention one common implementation error and correction.
  • Explain why prototype beans need explicit cleanup strategy.

Exam Preparation Questions: Long


  • Explain Spring IoC & Bean Life Cycle with architecture/flow and implementation steps.
  • Write a structured answer comparing two approaches used in this topic.
  • Discuss debugging strategy for this topic with likely failure points.
  • Design lifecycle handling for a bean that opens external resources at startup.

Practice Task


  • Implement: Register bean and verify init/destroy callback execution.
  • Add console/log output to validate flow step-by-step.
  • Document one bug you encountered and the exact fix.

Checklist


Can you:

  • explain Spring IoC & Bean Life Cycle in your own words?
  • implement a basic example end-to-end?
  • identify and fix one common runtime issue?

Next Lecture


  • Topic: Lecture 27 - Bean Scopes: Singleton, Prototype, Request, Session, Application
  • Preparation required: revise this lecture summary and code walkthrough

Questions?

Next: Lecture 27