Spring 允許在 Bean 在初始化完成后以及 Bean 銷毀前執(zhí)行特定的操作,常用的設定方式有以下三種:
通過Bean實現 InitializingBean/DisposableBean 接口來定制初始化之后/銷毀之前的操作方法;【缺點:要依賴Spring】
通過 <bean> 元素的 init-method/destroy-method屬性指定初始化之后 /銷毀之前調用的操作方法;(也可以不是xml配置,而是在@Bean上注解,效果相同)【優(yōu)點:不依賴于Spring的接口】
在指定方法上加上@PostConstruct 或@PreDestroy 注解來制定該方法是在初始化之后還是銷毀之前調用【在servlet中,要考慮的執(zhí)行流程是:servlet構造函數 > PostConstruct > init() > service() > destory() > PreDestroy】
注意:子類實例化過程中會調用父類中的@PostConstruct方法!
但他們之前并不等價。即使3個方法都用上了,也有先后順序.
Bean在實例化的過程中:Constructor > @PostConstruct >InitializingBean > init-method
Bean在銷毀的過程中:@PreDestroy > DisposableBean > destroy-method
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InitAndDestroySeqBean implements InitializingBean,DisposableBean {
public InitAndDestroySeqBean(){
System.out.println("執(zhí)行InitAndDestroySeqBean: 構造方法");
}
@PostConstruct
public void postConstruct() {
System.out.println("執(zhí)行InitAndDestroySeqBean: postConstruct");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("執(zhí)行InitAndDestroySeqBean: afterPropertiesSet");
}
public void initMethod() {
System.out.println("執(zhí)行InitAndDestroySeqBean: init-method");
}
@PreDestroy
public void preDestroy() {
System.out.println("執(zhí)行InitAndDestroySeqBean: preDestroy");
}
@Override
public void destroy() throws Exception {
System.out.println("執(zhí)行InitAndDestroySeqBean: destroy");
}
public void destroyMethod() {
System.out.println("執(zhí)行InitAndDestroySeqBean: destroy-method");
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/chj/spring/bean.xml");
context.close();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<bean id="initAndDestroySeqBean" class="com.chj.spring.InitAndDestroySeqBean" init-method="initMethod" destroy-method="destroyMethod"/>
</beans>