Spring4 - Beanのライフサイクル
singleton - クライアントはBeanのライフサイクルに関与できない prototype - コンテナーはBeanの生成後、ライフサイクルに関与できない
DI後の行為
- init-method属性
- InitializingBeanインタフェース
Bean破棄後の行為
- destory-method属性
- DisposableBeanインタフェース
共通的なinit-method,destory-method
- beans defalut-init-method...
- beans defalut-destory-method...
singletonのBeanにprototypeを注入する際の問題点
- lookup-method
ライフサイクルサンプル
package app.lifecycle; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; public class ObjectA implements InitializingBean, DisposableBean{ private String value1; private String value2; public void setValue1(String value1) { System.out.println("value1設定・・・"); this.value1 = value1; } public void setValue2(String value2) { System.out.println("value2設定・・・"); this.value2 = value2; } public ObjectA() { System.out.println("コンストラクター実行・・・"); } public void init() { System.out.println("初期化メソッド・・・"); } public void close() { System.out.println("破棄メソッド・・・"); } @Override public void destroy() throws Exception { System.out.println("destroy・・・"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("afterPropertiesSet・・・"); } }
<?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- Bean定義 --> <bean id="objectA" class="app.lifecycle.ObjectA" init-method="init" destroy-method="close"> <!-- コンストラクタによるDI --> <property name="value1" value="1111" /> <property name="value2" value="2222" /> </bean> </beans>
package app.lifecycle; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestLifeCycle { public static void main(String[] args) { // Springコンテナー生成 AbstractApplicationContext context = new ClassPathXmlApplicationContext("lifeCycleBeans.xml"); // JVM終了時にコンテナーを破棄する context.registerShutdownHook(); } }
コンストラクター実行・・・ value1設定・・・ value2設定・・・ afterPropertiesSet・・・ 初期化メソッド・・・ destroy・・・ 破棄メソッド・・・