Spring Bean init-method 和 destroy-method範例


在Spring中,可以使用 init-method 和 destroy-method 在bean 組態檔案屬性用於在bean初始化和銷毀某些動作時。這是用來替代 InitializingBean和DisposableBean介面

範例

這裡有一個例子向您展示如何使用 init-method 和 destroy-method。
package com.yiibai.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 : applicationContext.xml, 在bean中定義了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.yiibai.customer.services.CustomerService" 
		init-method="initIt" destroy-method="cleanUp">
   		
		<property name="message" value="i'm property message" />
	</bean>
		
</beans>

執行下面的程式程式碼:

package com.tw511.common;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yiibai.customer.services.CustomerService;

public class App 
{
    public static void main( String[] args )
    {
    	ConfigurableApplicationContext context = 
		new ClassPathXmlApplicationContext(new String[] {"applicationContext.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.yiibai.customer.services.CustomerService@5f49d886 
Spring Container is destroy! Customer clean up

 initIt()方法被呼叫,訊息屬性設定後,在 context.close()呼叫後,執行 cleanUp()方法;
建議使用init-method 和 destroy-methodbean 在Bena組態檔案,而不是執行 InitializingBean 和 DisposableBean 介面,也會造成不必要的耦合程式碼在Spring。

下載原始碼 – http://pan.baidu.com/s/1hreksq4