Spring InitializingBeanおよびDisposableBeanの例
Springでは、InitializingBeanとDisposableBeanは2つのマーカーインターフェイスであり、SpringがBeanの初期化と破棄時に特定のアクションを実行するための便利な方法です。
-
Beanで実装されたInitializingBeanの場合、すべてのBeanプロパティが設定された後、
afterPropertiesSet()が実行されます。 -
Beanで実装されたDisposableBeanの場合、SpringコンテナがBeanを解放した後、
destroy()を実行します。
例
InitializingBeanとDisposableBeanの使用方法を示す例を次に示します。 InitializingBeanインターフェイスとDisposableBeanインターフェイスの両方を実装するCustomerService Bean。メッセージプロパティがあります。
package com.example.customer.services;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class CustomerService implements InitializingBean, DisposableBean
{
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void afterPropertiesSet() throws Exception {
System.out.println("Init method after properties are set : " + message);
}
public void destroy() throws Exception {
System.out.println("Spring Container is destroy! Customer clean up");
}
}
ファイル:Spring-Customer.xml
それを実行します
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を破棄します。 destroy()メソッドのデモ目的でのみ使用されます:)
出力
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
メッセージプロパティが設定された後、afterPropertiesSet()メソッドが呼び出されます。一方、destroy()メソッドはcontext.close()の後に呼び出されます;
Thoughts…
コードをSpringに緊密に結合するため、InitializingBeanおよびDisposableBeanインターフェースの使用はお勧めしません。 より良いアプローチは、Bean構成ファイルでinit-method and destroy-method属性を指定することです。