Springでは、BeanのBean設定ファイルの属性として
init-method
と
destroy-method
属性を使用して、初期化と破棄時に特定のアクションを実行できます。
InitializingBeanおよびDisposableBeanインタフェース
の代わりになります。
例
package com.mkyong.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:BeanのSpring-Customer.xml
、
init-method
および
destroy-method
属性を定義します。
<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" init-method="initIt" destroy-method="cleanUp"> <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を破棄します。
出力
Init method after properties are set : i'm property message com.mkyong.customer.services.CustomerService@47393f ... INFO:org.springframework.beans.factoryのシングルトンを破棄する support.DefaultListableBeanFactory@77158a: 豆を定義する[customerService];工場階層の根 春のコンテナは破壊されています!顧客のクリーンアップ
-
initIt()** メソッドは、messageプロパティが設定された後に呼び出され、
-
cleanUp()** メソッドはcontext.close()の後に呼び出されます。
-
思考… **
-
init-method
と
destroy-method ** の使用は常に推奨されます。
Beanの設定ファイルではなく、InitializingBeanを実装する
DisposableBeanインターフェイス。不必要にコードを結合
春。
===ソースコードをダウンロードする
それをダウンロードする –
Spring -init-method-destroy-method-Example.zip
spring