π± Spring Bean Lifecycle¶
Spring beans donβt just appearβ¦ they go through a carefully choreographed life journey π From birth β preparation β service β retirement.
Letβs walk that lifecycle step by step.
πΉ 1. Bean Instantiation (Birth)¶
Spring creates the bean object.
π Bean is born using constructor or factory method.
πΉ 2. Populate Properties (Dependency Injection)¶
Spring injects dependencies:
π Like equipping the bean with tools π§°
πΉ 3. Aware Interfaces (Optional)¶
Bean gets context awareness:
BeanNameAwareApplicationContextAware
π βHey bean, you exist in this world, hereβs your identity.β
πΉ 4. BeanPostProcessor (Before Init)¶
Custom logic before initialization:
π Used for:
- Logging
- Proxy creation
- Modifications
πΉ 5. Initialization Phase¶
Two main ways:
β
Using @PostConstruct¶
β Using InitializingBean¶
π Bean is now fully ready π
πΉ 6. BeanPostProcessor (After Init)¶
π Often used for:
- AOP proxies
- Enhancements
πΉ 7. Bean Ready for Use¶
Now the bean is:
- Fully initialized
- Managed by Spring container
π This is where your business logic runs
πΉ 8. Destruction Phase (Shutdown)¶
When container shuts down:
β
Using @PreDestroy¶
β Using DisposableBean¶
π Cleanup resources (DB connections, threads, etc.)
π Full Lifecycle Flow¶
Instantiate β Inject Dependencies β Aware Interfaces β
BeanPostProcessor (Before) β Init β
BeanPostProcessor (After) β Ready β
Destroy
π― Interview Answer (Concise)¶
βSpring bean lifecycle includes instantiation, dependency injection, awareness callbacks, pre-initialization processing, initialization via @PostConstruct or InitializingBean, post-initialization processing, and finally destruction using @PreDestroy or DisposableBean.β
π§ Real Insight (Advanced)¶
-
BeanPostProcessor is heavily used internally by Spring for:
- AOP
- Transactions
- Security
π Thatβs how magic like @Transactional works β¨
β οΈ Common Mistakes¶
-
Forgetting that:
@PostConstructruns after dependency injection@PreDestroyonly works for singleton beans
π Memory Trick¶
Think of it like a startup employee π¨βπ»
- Hired (instantiate)
- Given tools (DI)
- Orientation (aware)
- Training (init)
- Works (ready)
- Exit interview (destroy)