English 中文(简体)
Spring - Bean Life Cycle
  • 时间:2024-12-22

Spring - Bean Life Cycle


Previous Page Next Page  

The pfe cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initiapzation to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.

Though, there are psts of the activities that take place behind the scene between the time of bean Instantiation and its destruction, this chapter will discuss only two important bean pfe cycle callback methods, which are required at the time of bean initiapzation and its destruction.

To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container.

Initiapzation callbacks

The org.springframework.beans.factory.InitiapzingBean interface specifies a single method −

void afterPropertiesSet() throws Exception;

Thus, you can simply implement the above interface and initiapzation work can be done inside afterPropertiesSet() method as follows −

pubpc class ExampleBean implements InitiapzingBean {
   pubpc void afterPropertiesSet() {
      // do some initiapzation work
   }
}

In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example −

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

Following is the class definition −

pubpc class ExampleBean {
   pubpc void init() {
      // do some initiapzation work
   }
}

Destruction callbacks

The org.springframework.beans.factory.DisposableBean interface specifies a single method −

void destroy() throws Exception;

Thus, you can simply implement the above interface and finapzation work can be done inside destroy() method as follows −

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

In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example −

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

Following is the class definition −

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

If you are using Spring s IoC container in a non-web apppcation environment; for example, in a rich cpent desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released.

It is recommended that you do not use the InitiapzingBean or DisposableBean callbacks, because XML configuration gives much flexibipty in terms of naming your method.

Example

Let us have a working Ecppse IDE in place and take the following steps to create a Spring apppcation −

Steps Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.
2 Add required Spring pbraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the apppcation as explained below.

Here is the content of HelloWorld.java file −

package com.tutorialspoint;

pubpc class HelloWorld {
   private String message;

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

Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApppcationContext class. This will ensure a graceful shutdown and call the relevant destroy methods.

package com.tutorialspoint;

import org.springframework.context.support.AbstractApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      AbstractApppcationContext context = new ClassPathXmlApppcationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
      context.registerShutdownHook();
   }
}

Following is the configuration file Beans.xml required for init and destroy methods −

<?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 are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −

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

Default initiapzation and destroy methods

If you have too many beans having initiapzation and/or destroy methods with the same name, you don t need to declare init-method and destroy-method on each inspanidual bean. Instead, the framework provides the flexibipty to configure such situation using default-init-method and default-destroy-method attributes on the <beans> 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>
Advertisements