Spring @PostConstructと@PreDestroyの例

Spring @PostConstructおよび@PreDestroyの例

Springでは、InitializingBean and DisposableBeanインターフェースを実装するか、初期化および破棄のコールバック関数のBean構成ファイルでinit-method and destroy-methodを指定できます。 この記事では、アノテーション@PostConstruct@PreDestroyを使用して同じことを行う方法を示します。

Note
@PostConstructおよび@PreDestroyアノテーションはSpringに属しておらず、J2eeライブラリ(common-annotations.jar)にあります。

@PostConstructおよび@PreDestroy

@PostConstructおよび@PreDestroyアノテーションを持つCustomerService Bean

package com.example.customer.services;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class CustomerService
{
    String message;

    public String getMessage() {
      return message;
    }

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

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

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

}

デフォルトでは、Springは@PostConstructおよび@PreDestroyアノテーションを認識しません。 これを有効にするには、「CommonAnnotationBeanPostProcessor」を登録するか、Bean構成ファイルで「<context:annotation-config />」を指定する必要があります。

1. CommonAnnotationBeanPostProcessor



    

    
        
    

2.



    

    
        
    

それを実行します

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

出力

Init method after properties are set : im 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() method (@PostConstruct)が呼び出され、context.close();の後にcleanUp() method (@PreDestroy)が呼び出されます。

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