Spring容器中的Bean是有生命周期,Spring 允许 Bean 在初始化完成后以及销毁前执行特定的操作。下面是常用的三种指定特定操作的方法:
- 通过实现InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
- 通过<bean> 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;
- 在指定方法上加上@PostConstruct或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。
xml配置
<bean id="myInitializingBean" class="com.sf.sfbuy2.context.filter.MyInitializingBean">
</bean>
<bean id="myXmlBean" class="com.sf.sfbuy2.context.filter.MyXmlBean" init-method="initMethod" destroy-method="destroyMethod"></bean>
<bean id="myAnnoationBean" class="com.sf.sfbuy2.context.filter.MyAnnoationBean"></bean>
方法一
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyInitializingBean implements InitializingBean,DisposableBean{
public MyInitializingBean(){
System.out.println("执行InitAndDestroySeqBean: 构造方法");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("执行InitAndDestroySeqBean: afterPropertiesSet");
}
@PreDestroy
public void preDestroy() {
System.out.println("执行InitAndDestroySeqBean: preDestroy");
}
@Override
public void destroy() throws Exception {
System.out.println("执行InitAndDestroySeqBean: destroy");
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.close();
}
}
方法二、
public class MyXmlBean{
public MyXmlBean(){
System.out.println("执行MyXmlBean: 构造方法");
}
public void initMethod() {
System.out.println("执行MyXmlBean: init-method");
}
public void destroyMethod() {
System.out.println("执行MyXmlBean: destroy-method");
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.close();
}
}
方法三、
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyAnnoationBean{
public MyAnnoationBean(){
System.out.println("执行myAnnoationBean: 构造方法");
}
@PostConstruct
public void postConstructMethod() {
System.out.println("执行myAnnoationBean: postConstructMethod初始化方法");
}
@PreDestroy
public void preDestroyMethod() {
System.out.println("执行myAnnoationBean: destroy-method销毁方法");
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.close();
}
}
Bean在实例化的过程中:Constructor > @PostConstruct >InitializingBean > init-method
Bean在销毁的过程中:@PreDestroy > DisposableBean > destroy-method