Spring Bean Life Cycles
1. What is Spring Bean Lifecycle?
- Lifecycle of an individual bean managed by the container.
- key annotation :
@PostConstruct,@PreDestroy,InitializingBean, etc. - Includes : Instantiation, Dependency Injection, Init & destroy callbacks.
2. Life Cycle Method
- Instantiation – Spring creates the bean object.
- Populate properties / Dependency Injection – Spring injects values or references.
- BeanNameAware / BeanFactoryAware callbacks – Optional callbacks if implemented.
- Pre-initialization –
@PostConstructorafterPropertiesSet()(from InitializingBean). - Custom init method – Optional method defined by
init-method. - Bean is ready to use – Application uses the bean.
- Destruction – Container shuts down;
@PreDestroy,destroy()(fromDisposableBean), ordestroy-methodis called.
3. Ways to Define Lifecycle Methods
1. Using xml
- Spring provide two method to every bean .
- Good for 3rd-party or external classes.
- we can change the name of these method but signature must be same
public void init(): Called after creation via config.Initialization code loading config,connecting db,webservice .public void distroy():For clean up code
Example Code
2. Using Interface
afterPropertiesSet(): called after dependencies are injected.destroy(): called when container shuts down.
Example Code
3. Using Annotation
- Recommended modern approach
@PostConstruct: Called after bean is created & dependencies injected@PreDestroy: called before bean is removed from container.
Example Code
@Component
public class Student {
public Student(){}
@PostConstruct
public void init() {
System.out.println("Bean is initialized");
}
@PreDestroy
public void cleanup() {
System.out.println("Bean is destroyed");
}
public void init2(){
System.out.println("Bean is initialized again");
}
public void cleanup2() {
System.out.println("Bean is destroyed again");
}
}
public class AppConfig{
@Bean(initMethod = "init2", destroyMethod = "cleanup2")
public Student student2(){
return new Student();
}
}
All 4 methods will be called, in this order:
- Initialization Order (on startup):
@PostConstruct:init()-
@Bean(initMethod = "..."):init2() -
Destruction Order (on shutdown):
@PreDestroy:cleanup()@Bean(destroyMethod = "..."):cleanup2()
4. Question
1. Is it possible to execute logic when a bean object created?
YES,Ways to Execute Logic After Bean Creation:
init-methodin XML or@Bean@PostConstructusing annotationInitializingBean.afterPropertiesSet()using interface
2. Difference Between singleton and prototype scope (Bean Lifecycle Perspective)
-
Singleton
- Created once at container startup
@PreDestroy/destroy(): Called by Spring when context is closed- Bean Destruction Responsibility : Spring container
-
Prototype
- Created every time the bean is requested.
@PreDestroy/destroy(): Not called automatically- Bean Destruction Responsibility : must be handle manually.
Github Code : Bean Life Cycle : Spring