Springでは、
InitializingBean
と
DisposableBean
は2つのマーカーインタフェースです.BeanがBeanの初期化と破棄時に特定のアクションを実行するのに便利な方法です。
-
Bean実装のInitializingBeanの場合、実行されます
`afterPropertiesSet()`はすべてのBeanプロパティが設定された後です。
-
Beanで実装されたDisposableBeanの場合、 `destroy()`を実行します
SpringコンテナがBeanから解放されます。
例
package com.mkyong.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");
}
}
File:Spring-Customer.xml
<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-2.5.xsd">
<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
<property name="message" value="i'm property message"/>
</bean>
</beans>
それを実行します
package com.mkyong.common;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.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.mkyong.customer.services.CustomerService@47393f ... INFO:org.springframework.beans.factoryのシングルトンを破棄する support.DefaultListableBeanFactory@77158a: 豆を定義する[customerService];工場階層の根 春のコンテナは破壊されています!顧客のクリーンアップ
メッセージプロパティの後にafterPropertiesSet()メソッドが呼び出されます。
セット; destroy()メソッドはcontext.close()の後にコールされます。
-
思考… **
InitializingBeanとDisposableBeanの使用をお勧めしません
それはあなたのコードをSpringに強く結びつけるからです。より良い
アプローチは、
リンク://spring/spring-init-method-and-destroy-method-example/[init-method
destroy-method]属性を使用します。
===ソースコードをダウンロードする
それをダウンロードする –
Spring-InitializingBean-DisposableBean-Example.zip
===参考文献