This project demonstrates the various stages of a Spring Bean's life, specifically focusing on the Initialization and Destruction phases.
Spring provides three ways to hook into the bean lifecycle:
- Mechanism: Define
init-methodanddestroy-methodin 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.
- Mechanism: Implement
InitializingBean(afterPropertiesSet) andDisposableBean(destroy). - Pros: Type-safe (compiler ensures methods exist).
- Cons: Couples your code tightly to the Spring Framework API.
- Mechanism: Use
@PostConstructand@PreDestroyannotations. - Pros: Very readable and follows standard Java (JSR-250) specifications.
- Requirement: Needs
<context:annotation-config/>or theCommonAnnotationBeanPostProcessorbean.
org.spring.bean.lifecycle/
├── usingXMLConfiguration/ # Approach 1: XML attributes
├── usingProgrammaticApproach/ # Approach 2: Interfaces
└── usingAnnotations/ # Approach 3: JSR-250 Annotations
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)
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!