Spring - Bean 生命周期

Spring bean 的生命周期很容易理解。 实例化 bean 时,可能需要执行一些初始化以使其进入可用状态。 同样,当不再需要 bean 并将其从容器中取出时,可能需要进行一些清理。

虽然有一些在 bean 实例化和销毁之间幕后发生的活动的列表,但本章将只讨论两个重要的 bean 生命周期回调方法,它们是 bean 初始化和销毁时所需的。

要为 bean 定义设置和销毁,我们只需使用 initmethod 和/或 destroy-method 参数声明 <bean>。 init-method 属性指定了在实例化时立即在 bean 上调用的方法。 类似地,destroymethod 指定了一个在从容器中删除 bean 之前调用的方法。


初始化回调

org.springframework.beans.factory.InitializingBean 接口指定单个方法 −

void afterPropertiesSet() throws Exception;

因此,您可以简单地实现上述接口,并且可以在 afterPropertiesSet() 方法中完成初始化工作,如下所示 −

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

在基于 XML 的配置元数据的情况下,您可以使用 init-method 属性来指定具有 void 无参数签名的方法的名称。 例如 −

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

下面是类的定义 −

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

销毁回调

org.springframework.beans.factory.DisposableBean 接口指定一个方法 −

void destroy() throws Exception;

因此,您可以简单地实现上述接口,并且可以在destroy() 方法中完成如下工作 −

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

在基于 XML 的配置元数据的情况下,您可以使用 destroy-method 属性来指定具有 void 无参数签名的方法的名称。 例如 −

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

下面是类的定义 −

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

如果你在非 web 应用环境中使用 Spring 的 IoC 容器; 例如,在 rich 客户端桌面环境中,您向 JVM 注册了一个关闭 hook。 这样做可确保正常关闭并在单例 bean 上调用相关的销毁方法,以便释放所有资源。

建议不要使用 InitializingBean 和 DisposableBean 回调,因为 XML 配置在命名方法方面提供了很大的灵活性。

示例

让我们有一个可以工作的 Eclipse IDE,并按照以下步骤创建一个 Spring 应用程序 −

步骤 描述
1 创建一个名为 SpringExample 的项目,并在创建的项目中的 src 文件夹下创建一个包 com.tutorialspoint
2 使用 Add External JARs 选项添加所需的 Spring 库,如 Spring Hello World 示例 一章中所述。
3 com.tutorialspoint 包下创建 Java 类 HelloWorldMainApp
4 src 文件夹下创建 Beans 配置文件 Beans.xml
5 最后一步是创建所有 Java 文件和 Bean 配置文件的内容并运行应用程序,如下所述。

这是 HelloWorld.java 文件的内容 −

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.");
   }
}

以下是 MainApp.java 文件的内容。 这里需要注册一个在 AbstractApplicationContext 类上声明的关闭 hook registerShutdownHook() 方法。 这将确保正常关闭并调用相关的销毁方法。

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();
   }
}

以下是 init 和 destroy 方法所需的配置文件 Beans.xml

<?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>

完成创建源和 bean 配置文件后,让我们运行应用程序。 如果您的应用程序一切正常,它将打印以下消息 −

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

默认初始化和销毁方法

如果您有太多具有相同名称的初始化和/或销毁方法的 bean,则无需在每个 bean 上声明 init-methoddestroy-method . 相反,框架提供了使用 <beans> 元素上的 default-init-methoddefault-destroy-method 属性配置这种情况的灵活性,如下所示 −

<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>