Springのinitメソッドとdestroyメソッドの例

Spring init-methodおよびdestroy-methodの例

Springでは、init-methodおよびdestroy-methodをBean構成ファイルの属性として使用して、初期化および破棄時に特定のアクションを実行できます。 InitializingBean and DisposableBean interfaceの代替。

init-methoddestroy-methodの使用方法を示す例を次に示します。

package com.example.customer.services;

public class CustomerService
{
    String message;

    public String getMessage() {
      return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }

    public void initIt() throws Exception {
      System.out.println("Init method after properties are set : " + message);
    }

    public void cleanUp() throws Exception {
      System.out.println("Spring Container is destroy! Customer clean up");
    }

}

File : Spring-Customer.xml、Beanでinit-methodおよびdestroy-method属性を定義します。



    

        
    

それを実行します

package com.example.common;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.customer.services.CustomerService;

public class App
{
    public static void main( String[] args )
    {
        ConfigurableApplicationContext context =
        new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});

        CustomerService cust = (CustomerService)context.getBean("customerService");

        System.out.println(cust);

        context.close();
    }
}

ConfigurableApplicationContext.closeは、アプリケーションコンテキストを閉じ、すべてのリソースを解放し、キャッシュされたすべてのシングルトンBeanを破棄します。
_
Output_

Init method after properties are set : i'm property message
com.example.customer.services.CustomerService@47393f
...
INFO: Destroying singletons in org.springframework.beans.factory.
support.DefaultListableBeanFactory@77158a:
defining beans [customerService]; root of factory hierarchy
Spring Container is destroy! Customer clean up

メッセージプロパティが設定された後、initIt()メソッドが呼び出され、context.close();の後にcleanUp()メソッドが呼び出されます。

Thoughts…
コードをSpringに不必要に結合させるために、InitializingBeanおよびDisposableBeanインターフェースを実装するのではなく、Bean構成ファイルでinit-methodおよびdestroy-methodを使用することを常にお勧めします。

ソースコードをダウンロード