Spring – Bean Lifecycle

Spring bean is responsible for managing the lifecycle of beans created by the Spring container.  The lifecycle of the bean is easy to understand. When a bean is created, it requires some initialization code to get into a usable state. Similarly, when the bean is no longer in use or removed from the Spring container, some cleanup code may be required.

To startup and shutdown a bean, we declare the init-method and the destroy-method attributes inside the <bean> tag in the bean-configuration file.

Init- method – It specifies a process which is called on the bean during the instantiation. We can give any name to the init-method.

Following code shows how to declare the init-method:

Destroy-method ­­­­­– It defines a process which is called on the bean before it is removed from the Spring container. Like the init- method, we can give any name to the destroy-method.

Following code shows how to declare the destroy-method:

Example of Bean Lifecycle

Let’s understand the lifecycle of the Spring beans with the help of an example. In this example, we are going to create an interface Sim, which contains an unimplemented method calling(). A class Airtel_Sim implements the Sim interface and its unimplemented method.

Following are the steps to create this example:

Sim.java

Airtel_Sim.java

In the above Airtel_Sim class, we have initialized the init (doStartUp) and destroy (doShutDowm) methods. There is no particular name available for these two methods. We can give any name to the init and destroy methods.   

In the bean-config file (applicationContext), we need to add the entry of the init method and destroy method. So, we are going to add the entry inside the <bean> tag.

applicationContext.xml

App.java

Output

Spring container does not manage the prototype bean completely

The Spring does not call the destroy method for the prototype scope. In contrast to the other bean scopes, the Spring container does not manage the prototype bean completely.

Pin It on Pinterest

Share This