Spring Bean InitializingBean和DisposableBean實例


在Spring中,InitializingBean和DisposableBean是兩個標記接口,為Spring執行時bean的初始化和銷毀某些行為時的有用方法。
  1. 對於Bean實現 InitializingBean,它將運行 afterPropertiesSet()在所有的 bean 屬性被設置之后。
  2. 對於 Bean 實現了DisposableBean,它將運行 destroy()在 Spring 容器釋放該 bean 之后。

示例

下面是一個例子,向您展示如何使用 InitializingBean 和 DisposableBean。一個 CustomerService bean來實現 InitializingBean和DisposableBean 接口,並有一個消息(message)屬性。
package com.yiibai.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 : applicationContext.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.yiibai.customer.services.CustomerService">
		<property name="message" value="I'm property message" />
       </bean>
		
</beans>

執行它

package com.yiibai.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。它是只用於 destroy() 方的演示目的。

輸出結果

Init method after properties are set : I'm property message 
com.yiibai.customer.services.CustomerService@4090c06f 
Spring Container is destroy! Customer clean up

 

afterPropertiesSet()方法被調用在 message 屬性設置后,而 destroy()方法是在調用 context.close()之后;
 
建議:
不建議使用InitializingBean和DisposableBean的接口,因為它將你的代碼緊耦合到 Spring 代碼中。 一個更好的做法應該是在bean的配置文件屬性指定  init-method和destroy-method
 
下載代碼 –  http://pan.baidu.com/s/1nu3cEXN


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM