Search This Blog

Tuesday, September 1, 2020

Bean Lifecycle??

 Bean Lifecycle??

When container starts – a Spring bean needs to be instantiated, based on Java or XML bean definition. It may also be required to perform some post-initialization steps to get it into a usable state. Same bean life cycle is for spring boot applications as well.

After that, when the bean is no longer required, it will be removed from the IoC container.

Spring bean factory is responsible for managing the life cycle of beans created through spring container.

1.1. Life cycle callbacks

Spring bean factory controls the creation and destruction of beans. To execute some custom code, it provides the call back methods which can be categorized broadly in two groups:

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

1.1. Life cycle in diagram

Spring Bean Life Cycle
Spring Bean Life Cycle

2. Life cycle callback methods

Spring framework provides following 4 ways for controlling life cycle events of a bean:

  1. InitializingBean and DisposableBean callback interfaces
  2. *Aware interfaces for specific behavior
  3. Custom init() and destroy() methods in bean configuration file
  4. @PostConstruct and @PreDestroy annotations

2.1. InitializingBean and DisposableBean

The org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container.

The InitializingBean interface specifies a single method:

InitializingBean.java
void afterPropertiesSet() throws Exception;

This is not a preferrable way to initialize the bean because it tightly couple your bean class with spring container. A better approach is to use “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.


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

No comments:

Post a Comment