问题描述
小弟初学spring,可是在销毁bean的时候,代码如下:applicationContext.xml<beans <br="">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="user" class="com.xznu.springdemo.UserBean" <br="">abstract="false" lazy-init="default" autowire="default"dependency-check="default" ></bean></beans>UserBean.javapackage com.xznu.springdemo;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.InitializingBean;public class UserBean implements InitializingBean,DisposableBean{private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public void afterPropertiesSet() throws Exception {// 继承初始化接口name = "wwx";age = 23;}public void destroy() throws Exception {// 继承销毁接口name = null;age = 0;System.out.println("以销毁!"+this.name);}}MainDemo.javapackage com.xznu.springdemo;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class MainDemo {public static void main(String args[]){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");UserBean userBean = (UserBean)context.getBean("user");System.out.println("name:"+userBean.getName());System.out.println("age:"+userBean.getAge());}}只能初始化,却能销毁Bean,,不知道怎么回事?十分郁闷。。望高手给解决一下!谢谢!
解决方案
你的问题应该是: 只能初始化,却不能销毁Bean 吧.之所以没有依据你的预期调用DisposableBean.destroy()方法,是由于,整段代码结束了. 哈哈.将代码改成下面这样:public static void main(String args[]) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("user.xml");context.registerShutdownHook();UserBean userBean = (UserBean) context.getBean("user");System.out.println("name:" + userBean.getName());System.out.println("age:" + userBean.getAge());}注意这一句: context.registerShutdownHook();其实, 它内部就是给 Runtime.getRuntime().addShutdownHook(this.shutdownHook);也就是在jvm停掉之前执行 this.shutdownHook 里面定义的事情.只有使用context.registerShutdownHook(); 注册了shutdownHook, 才可以触发剩下的事情, 比如说 DisposableBean.destroy()方法.
解决方案二:
记得 在Spring的文档的bean的生命周期一节中讲过了 ???