Skip to content

Spring Bean life Cycle

Vishnu Garg edited this page Aug 4, 2018 · 4 revisions

Spring Bean life Cycle

Spring bean factory is responsible for managing the life cycle of beans created through spring container. The life cycle of beans consist of call back methods which can be categorized broadly in two groups:

  • Post initialization call back methods
  • Pre destruction call back methods

Life Cycle Spring Bean Life Cycle Callback Methods

  • InitializingBean and DisposableBean callback interfaces
  • Other Aware interfaces for specific behavior
  • Custom init() and destroy() methods in bean configuration file
  • @PostConstruct and @PreDestroy annotations

Refrences https://howtodoinjava.com/spring-core/spring-bean-life-cycle/

1. InitializingBean and DisposableBean callback interfaces

init-method” attribute in bean definition in applicationContext.xml file. Similarly, implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies a single method:

3. Custom init() and destroy() methods in bean configuration file

The default init and destroy methods in bean configuration file can be defined in two ways: Bean local definition applicable to a single bean Global definition applicable to all beans defined in beans context Local definition is given as below.

<beans>
 
    <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"
                    init-method="customInit"
                    destroy-method="customDestroy"></bean>

<beans default-init-method="customInit" default-destroy-method="customDestroy">  
 
        <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"></bean>
 
</beans>
 
</beans>
```'
### 4)** @PostConstruct** and **@PreDestroy** annotations

@PostConstruct annotated method will be invoked after the bean has been constructed using default constructor and just before it’s instance is returned to requesting object.
@PreDestroy annotated method is called just before the bean is about be destroyed inside bean container.
Clone this wiki locally