Skip to content

Comprehensive guide to Spring Bean Lifecycle management. Demonstrates three approaches: XML configuration, Programmatic interfaces (InitializingBean/DisposableBean), and JSR-250 Annotations (@PostConstruct/@PreDestroy).

License

Notifications You must be signed in to change notification settings

harman-04/spring-bean-lifecycle-mastery

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Bean Lifecycle Exploration

This project demonstrates the various stages of a Spring Bean's life, specifically focusing on the Initialization and Destruction phases.

The Three Approaches

Spring provides three ways to hook into the bean lifecycle:

1. XML Configuration (Declarative)

  • Mechanism: Define init-method and destroy-method in the <bean> tag.
  • Pros: Keeps Java code clean of Spring-specific logic.
  • Cons: Errors are only caught at runtime if the method names don't match.

2. Programmatic Approach (Interface-based)

  • Mechanism: Implement InitializingBean (afterPropertiesSet) and DisposableBean (destroy).
  • Pros: Type-safe (compiler ensures methods exist).
  • Cons: Couples your code tightly to the Spring Framework API.

3. Annotation Approach (Modern/JSR-250)

  • Mechanism: Use @PostConstruct and @PreDestroy annotations.
  • Pros: Very readable and follows standard Java (JSR-250) specifications.
  • Requirement: Needs <context:annotation-config/> or the CommonAnnotationBeanPostProcessor bean.

Project Structure

org.spring.bean.lifecycle/
├── usingXMLConfiguration/    # Approach 1: XML attributes
├── usingProgrammaticApproach/ # Approach 2: Interfaces
└── usingAnnotations/          # Approach 3: JSR-250 Annotations

Execution Order

If you were to combine all three on a single bean, Spring follows this order:

1. @PostConstruct (Annotations)

2. afterPropertiesSet (Interface)

3. Custom init() (XML)

Usage

Each package contains a Client class. Run these individually to see the lifecycle messages printed to the console. Note: context.close() is vital to trigger the destruction phase!

About

Comprehensive guide to Spring Bean Lifecycle management. Demonstrates three approaches: XML configuration, Programmatic interfaces (InitializingBean/DisposableBean), and JSR-250 Annotations (@PostConstruct/@PreDestroy).

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages