1、 使用 @PreDestroy 注解
2、 @Bean(destroyMethod = "destroyMethod") 及xml中配置 destroy-method = "destroyMethod"
3、实现 DisposableBean接口中的 destroy 方法
@Configuration
public class SpringBeanDestroyDemo {
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(SpringBeanDestroyDemo.class);
//启动spring上下文
applicationContext.refresh();
//关闭spring上下文,才会触发bean销毁操作
applicationContext.close();
Thread.sleep(6000);
System.gc();
Thread.sleep(6000);
}
@Bean(destroyMethod = "destroyMethod")
public Role createRole(){
return new Role();
}
}
public class Role implements DisposableBean {
@PreDestroy
public void preDestroy(){
System.out.println("@PreDestroy destroy.....");
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean destroy.....");
}
public void destroyMethod(){
System.out.println("destroy-method destroy.....");
}
@Override
protected void finalize() throws Throwable {
System.out.println("Role 对象被垃圾收集器回收......");
}
}