Springの@PostConstructと@PreDestroy

Spring Beans依存性注入を使用して設定する場合、ビーンがクライアントのリクエストを処理する前にすべてが適切に初期化されていることを確認したい場合があります。同様に、コンテキストが破棄されると、Spring Beanが使用するいくつかのリソースをクローズする必要がある場合があります。

Spring @PostConstruct

Spring Beanのメソッドに@PostConstructアノテーションを付けると、Spring Beanの初期化後に実行されます。@PostConstructアノテーションが付いたメソッドは1つだけです。このアノテーションはCommon Annotations APIの一部であり、JDKモジュールjavax.annotation-apiの一部です。したがって、Java 9以降でこのアノテーションを使用している場合は、このjarファイルをプロジェクトに明示的に追加する必要があります。Mavenを使用している場合は、以下の依存関係を追加する必要があります。

<dependency>
	<groupId>javax.annotation</groupId>
	<artifactId>javax.annotation-api</artifactId>
	<version>1.3.2</version>
</dependency>

Java 8以下のバージョンを使用している場合は、上記の依存関係を追加する必要はありません。

Spring @PreDestroy

Spring BeanメソッドにPreDestroy注釈を付けると、Beanインスタンスがコンテキストから削除される際に呼び出されます。これは非常に重要なポイントです – もしSpring Beanのスコープが”prototype”である場合、それは完全にSpringコンテナによって管理されず、PreDestroyメソッドは呼び出されません。もしshutdownまたはcloseという名前のメソッドがある場合、SpringコンテナはBeanが破棄される際にそれらを自動的にコールバックメソッドとして構成しようとします。

Spring@PostConstruct@PreDestroyの例

以下は、@PostConstruct@PreDestroyメソッドを持つシンプルなSpring Beanです。

package com.journaldev.spring;

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

public class MyBean {

	public MyBean() {
		System.out.println("MyBean instance created");
	}

	@PostConstruct
	private void init() {
		System.out.println("Verifying Resources");
	}

	@PreDestroy
	private void shutdown() {
		System.out.println("Shutdown All Resources");
	}

	public void close() {
		System.out.println("Closing All Resources");
	}
}

注意してください。Beanが破棄される際にcloseメソッドが呼び出されるかどうかを確認するために、Springの設定クラスも定義しています。

package com.journaldev.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class MyConfiguration {
	
    @Bean
    @Scope(value="singleton")
    public MyBean myBean() {
	return new MyBean();
    }
	
}

I don’t need to explicitly specify my bean as a singleton but I will later change its value to “prototype” and see what happens with @PostConstruct and @PreDestroy methods. Here is my main class where I am creating spring context and getting few instances of MyBean.

package com.journaldev.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MySpringApp {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MyConfiguration.class);
		ctx.refresh();

		MyBean mb1 = ctx.getBean(MyBean.class);
		System.out.println(mb1.hashCode());

		MyBean mb2 = ctx.getBean(MyBean.class);
		System.out.println(mb2.hashCode());

		ctx.close();
	}

}

上記のクラスを実行すると、次の出力が得られます。

MyBean instance created
Verifying Resources
1640296160
1640296160
Shutdown All Resources
Closing All Resources

@PostConstructメソッドは、Beanがインスタンス化された後に呼び出されます。コンテキストが閉じられると、シャットダウンとクローズの両方のメソッドが呼び出されます。

Spring @PostConstruct@PreDestroyをプロトタイプスコープで使用する

MyConfigurationでスコープ値をprototypeに変更して、メインクラスを実行してください。以下のような出力が得られます。

MyBean instance created
Verifying Resources
1640296160
MyBean instance created
Verifying Resources
1863374262

これにより、SpringコンテナがリクエストごとにBeanを初期化し、その@PostConstructメソッドを呼び出してからクライアントに渡していることがわかります。その後、SpringはBeanを管理せず、この場合、クライアントはPreDestroyメソッドを直接呼び出してリソースのクリーンアップを行う必要があります。

要約

@PostConstruct@PreDestroyは、SpringのBeanライフサイクル管理と一緒に使用する重要なアノテーションです。これらを使用して、Beanが適切に初期化されたことを検証し、BeanがSpringコンテキストから削除されたときにすべてのリソースを閉じることができます。

詳細なプロジェクトコードは、GitHubリポジトリから確認できます。

Source:
https://www.digitalocean.com/community/tutorials/spring-postconstruct-predestroy