Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Spring Bean lifecycle


May 14, 2021 Spring


Table of contents


The life cycle of the bean

Understanding the lifecycle of Spring bean is easy. W hen a bean is instantiated, it may need to perform some initialization to convert it to an available state. Similarly, some cleanup may be required when the bean is no longer needed and removed from the container.

Although there are some activities that occur between bean instantiation and destruction, this chapter will discuss only two important lifecycle callback methods that are required for the initialization and destruction of beans.

In order to define the installation and removal of a bean, we simply declare a with init-method and/or destroy-method parameters. T he init-method property specifies a method that is called as soon as the bean is instantiated. Similarly, destroy-method specifies a method that cannot be called until the bean is removed from the container.

The life cycle of a bean can be expressed as the definition of a bean - the initialization of a bean - the use of a bean - the destruction of a bean

Initialize the callback

The org.springframework.beans.factory.InitializingBean interface specifies a single approach:

void afterPropertiesSet() throws Exception;

Therefore, you can simply implement the above interface and initialization work can be performed in the afterPropertiesSet() method, as follows:

public class ExampleBean implements InitializingBean {
   public void afterPropertiesSet() {
      // do some initialization work
   }
}

In the case of XML-based configuration metadata, you can use the init-method property to specify the name of a method with void no parameters. For example:

<bean id="exampleBean" 
         class="examples.ExampleBean" init-method="init"/>

Here's the definition of the class:

public class ExampleBean {
   public void init() {
      // do some initialization work
   }
}

Destroy callbacks

The org.springframework.beans.factory.DisposableBean interface specifies a single approach:

void destroy() throws Exception;

Therefore, you can simply implement the above interface and finish the work can be performed in the destroy() method, as follows:

public class ExampleBean implements DisposableBean {
   public void destroy() {
      // do some destruction work
   }
}

In the case of XML-based configuration metadata, you can use the destroy-method property to specify the name of a method with void without parameters. For example:

<bean id="exampleBean"
         class="examples.ExampleBean" destroy-method="destroy"/>

Here's the definition of the class:

public class ExampleBean {
   public void destroy() {
      // do some destruction work
   }
}

If you use Spring's IoC container in a non-web application environment, for example, in a rich client desktop environment, you want to register to close hooks in JVM. Doing so ensures a normal shutdown, and in order for all resources to be freed, the destroy method can be called on a single beans.

It is recommended that you do not use the callback methods of InitializingBean or DisposableBean, because XML configuration provides a great deal of flexibility in naming methods.

Example

We use the Eclipse IDE in the right place, and then follow these steps to create a Spring application:

Steps Describe
1 Create a project named SpringExample, and create a package com.tutorialspoint in the src folder that created the project.
2 Use the Add External JARs option to add the Spring library you want, as explained in the Spring Hello World Example section.
3 Create Java-like HelloWorld and MainApp in the com.tutorialspoint package.
4 Create the Beans profile Beans file in the src .xml.
5 The final step is to create the contents of all Java files and bean profiles and run the application as explained below.

Here's what .java HelloWorld files:

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
   public void init(){
      System.out.println("Bean is going through init.");
   }
   public void destroy(){
      System.out.println("Bean will destroy now.");
   }
}

Below is the contents .java mainApp file. H ere, you need to register a registerShutdown Hook() method for closing hooks declared in the Abstract ApplicationContext class. It will ensure a normal shutdown and call the relevant destroy method.

package com.tutorialspoint;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
   public static void main(String[] args) {
      AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
      context.registerShutdownHook();
   }
}

Here are the profile Beans files that are required for the init .xml method:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" 
       class="com.tutorialspoint.HelloWorld"
       init-method="init" destroy-method="destroy">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

Once you've created the source code and bean profile, we're ready to run the application. If everything is fine with your application, the following information will be output:

Bean is going through init.
Your Message : Hello World!
Bean will destroy now.

The default initialization and destruction method

If you have too many beans with the same name for initialization or destruction methods, you do not need to declare initialization methods and destruction methods on each bean. The framework provides the flexibility to configure this situation using the default-init-method and default-destroy-method properties in the element, as follows:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    default-init-method="init" 
    default-destroy-method="destroy">

   <bean id="..." class="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

</beans>