Spring Bean 生命周期

2022-05-21 15:22 更新

理解 Spring bean 的生命周期很容易。當一個 bean 被實例化時,它可能需要執(zhí)行一些初始化使它轉(zhuǎn)換成可用狀態(tài)。同樣,當 bean 不再需要,并且從容器中移除時,可能需要做一些清除工作。

盡管還有一些在 Bean 實例化和銷毀之間發(fā)生的活動,但是本章將只討論兩個重要的生命周期回調(diào)方法,它們在 bean 的初始化和銷毀的時候是必需的。

為了定義安裝和拆卸一個 bean,我們只要聲明帶有 init-method 和/或 destroy-method 參數(shù)的 。init-method 屬性指定一個方法,在實例化 bean 時,立即調(diào)用該方法。同樣,destroy-method 指定一個方法,只有從容器中移除 bean 之后,才能調(diào)用該方法。

Bean的生命周期可以表達為:Bean的定義——Bean的初始化——Bean的使用——Bean的銷毀

初始化回調(diào)

org.springframework.beans.factory.InitializingBean 接口指定一個單一的方法:

void afterPropertiesSet() throws Exception;

因此,你可以簡單地實現(xiàn)上述接口和初始化工作可以在 afterPropertiesSet() 方法中執(zhí)行,如下所示:

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

在基于 XML 的配置元數(shù)據(jù)的情況下,你可以使用 init-method 屬性來指定帶有 void 無參數(shù)方法的名稱。例如:

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

下面是類的定義:

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

銷毀回調(diào)

org.springframework.beans.factory.DisposableBean 接口指定一個單一的方法:

void destroy() throws Exception;

因此,你可以簡單地實現(xiàn)上述接口并且結(jié)束工作可以在 destroy() 方法中執(zhí)行,如下所示:

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

在基于 XML 的配置元數(shù)據(jù)的情況下,你可以使用 destroy-method 屬性來指定帶有 void 無參數(shù)方法的名稱。例如:

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

下面是類的定義:

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

如果你在非 web 應(yīng)用程序環(huán)境中使用 Spring 的 IoC 容器;例如在豐富的客戶端桌面環(huán)境中;那么在 JVM 中你要注冊關(guān)閉 hook。這樣做可以確保正常關(guān)閉,為了讓所有的資源都被釋放,可以在單個 beans 上調(diào)用 destroy 方法。

建議你不要使用 InitializingBean 或者 DisposableBean 的回調(diào)方法,因為 XML 配置在命名方法上提供了極大的靈活性。

例子

我們在適當?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟來創(chuàng)建一個 Spring 應(yīng)用程序:

步驟 描述
1 創(chuàng)建一個名稱為 SpringExample 的項目,并且在創(chuàng)建項目的 src 文件夾中創(chuàng)建一個包 com.tutorialspoint。
2 使用 Add External JARs 選項,添加所需的 Spring 庫,解釋見 Spring Hello World Example 章節(jié)。
3 com.tutorialspoint 包中創(chuàng)建 Java 類 HelloWorldMainApp。
4 src 文件夾中創(chuàng)建 Beans 配置文件 Beans.xml
5 最后一步是創(chuàng)建的所有 Java 文件和 Bean 配置文件的內(nèi)容,并運行應(yīng)用程序,解釋如下所示。

這里是 HelloWorld.java 的文件的內(nèi)容:

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 文件的內(nèi)容。在這里,你需要注冊一個在 AbstractApplicationContext 類中聲明的關(guān)閉 hook 的 registerShutdownHook() 方法。它將確保正常關(guān)閉,并且調(diào)用相關(guān)的 destroy 方法。

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>

一旦你創(chuàng)建源代碼和 bean 配置文件完成后,我們就可以運行該應(yīng)用程序。如果你的應(yīng)用程序一切都正常,將輸出以下信息:

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

默認的初始化和銷毀方法

如果你有太多具有相同名稱的初始化或者銷毀方法的 Bean,那么你不需要在每一個 bean 上聲明初始化方法銷毀方法。框架使用 元素中的 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>
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號