Spring-bean-life-cycle

提供:Dev Guides
移動先:案内検索

春-Beanのライフサイクル

Spring Beanのライフサイクルは簡単に理解できます。 Beanがインスタンス化されるとき、使用可能な状態にするために何らかの初期化を実行する必要がある場合があります。 同様に、Beanが不要になり、コンテナから削除されると、クリーンアップが必要になる場合があります。

Beanのインスタンス化とその破棄の間に舞台裏で行われるアクティビティのリストがありますが、この章では、Beanの初期化と破棄のときに必要な2つの重要な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 属性を使用して、引数なしの無効な署名を持つメソッドの名前を指定できます。 たとえば-

<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コンテナーを使用している場合。たとえば、リッチクライアントデスクトップ環境では、シャットダウンフックをJVMに登録します。 これにより、正常なシャットダウンが保証され、シングルトンBeanの関連するdestroyメソッドが呼び出され、すべてのリソースが解放されます。

XML構成はメソッドの命名に関して非常に柔軟性があるため、InitializingBeanまたはDisposableBeanコールバックを使用しないことをお勧めします。

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.finddevguides 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 application as explained below.
*HelloWorld.java* ファイルの内容は次のとおりです-
package com.finddevguides;

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クラスで宣言されているシャットダウンフック* registerShutdownHook()*メソッドを登録する必要があります。 これにより、正常なシャットダウンが保証され、関連する破棄メソッドが呼び出されます。

package com.finddevguides;

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.finddevguides.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-method および default-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>