Spring bean life cycle



Que: -What is spring bean life cycle?

Spring container controls life cycle of spring bean that is from bean instantiation to destruction. Spring bean is a POJO it need not implement any spring specific API interfaces or extend any classes so as to facilitate the spring container to controls life cycle i.e. for spring bean component contract is not required.

Spring bean has four life cycle phases:

  1. Instantiation phase
  2. Initialization phase
  3. Ready to use/servicing phase
  4. Destruction phase

Spring bean life cycle is described as follows:

1. Instantiation phase: –

Spring container loads spring bean class into memory and creates the bean instance. When the spring bean instance is created, spring container uses dependency injection to populate the bean fields. All the dependencies are configured for the spring bean before its initialization finished.

2. Initialization phase: –

In the spring bean class if any custom initialization method is specified, spring container calls that method. In this method we can give any resource to the spring bean.

Note: –Unless initialization phase is over, spring container does not give bean references to the caller.

In case of BeanFactory, instantiation and initialization happens then getBean() method is called.

3. Ready to use phase: –

When spring container gives the bean references to the caller, its business method can be called.

4. Destruction phase: –

Upon container shutdown or any explicit method is called, spring container calls the user defined destroy() method of the spring bean. Just before the bean instance is garbage collected. In this method, we release the resources allocated to the bean.

Que: -How to create custom initialization method for a spring bean?

Step 1: –In the spring bean class implement any user defined method with any name.

Step 2: –In the spring configuration file make use of “init-method” attribute in the <bean> tag and specify the user defined method name as value to that attribute.

Que: -How to specify custom destruction() method for a spring bean?

Step 1: –In the spring bean class implement any user defined method.

Step 2: –In the <bean> tag make use of “destroy method” attribute and specify the user defined destroy method name as value to the attribute.


Share Button

One thought on “Spring bean life cycle

Leave a Reply

Your email address will not be published. Required fields are marked *