Spring Bean init-method 和 destroy-method實例

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

示例

這裏有一個例子向您展示如何使用 init-method 和 destroy-method。
package com.zaixian.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.zaixian.customer.services.CustomerService"
		init-method="initIt" destroy-method="cleanUp">

		<property name="message" value="i'm property message" />
	</bean>

</beans>

執行下麵的程式代碼:

package com.xuhuhu.common;

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

import com.zaixian.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.zaixian.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

上一篇: Spring Bean InitializingBean和DisposableBean實例 下一篇: Spring @PostConstruct和@PreDestroy實例