在Spring中,InitializingBean和DisposableBean是兩個標記介面,為Spring執行時bean的初始化和銷毀某些行為時的有用方法。
-
對於Bean實現 InitializingBean,它將運行 afterPropertiesSet()在所有的 bean 屬性被設置之後。
-
對於 Bean 實現了DisposableBean,它將運行 destroy()在 Spring 容器釋放該 bean 之後。
示例
下麵是一個例子,向您展示如何使用 InitializingBean 和 DisposableBean。一個 CustomerService bean來實現 InitializingBean和DisposableBean 介面,並有一個消息(message)屬性。
package com.zaixian.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.zaixian.customer.services.CustomerService">
<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。它是只用於 destroy() 方的演示目的。
輸出結果
Init method after properties are set : I'm property message com.zaixian.customer.services.CustomerService@4090c06f Spring Container is destroy! Customer clean up
afterPropertiesSet()方法被調用在 message 屬性設置後,而 destroy()方法是在調用 context.close()之後;
建議:
不建議使用InitializingBean和DisposableBean的介面,因為它將你的代碼緊耦合到 Spring 代碼中。 一個更好的做法應該是在bean的配置檔屬性指定 init-method和destroy-method。
不建議使用InitializingBean和DisposableBean的介面,因為它將你的代碼緊耦合到 Spring 代碼中。 一個更好的做法應該是在bean的配置檔屬性指定 init-method和destroy-method。
