Spring初始化和销毁方法
} 对于xml上下文,我有:Spring初始化和销毁方法,spring,methods,init,destroy,Spring,Methods,Init,Destroy,} 对于xml上下文,我有: package com.idol; public class Auditorium { Auditorium(){ } public void turnOnLights() { System.out.println("Lights are turned on"); } public void turnOffLights(){ System.out.println("Lights are turned off"); }
package com.idol;
public class Auditorium {
Auditorium(){
}
public void turnOnLights() {
System.out.println("Lights are turned on");
}
public void turnOffLights(){
System.out.println("Lights are turned off");
}
我得到:
只打印“灯已打开”,不打印“灯已关闭”。我认为在销毁bean之前,它也应该调用destroy方法,我缺少或没有得到什么?(我在日志中没有错误,以防万一)
谢谢像这样试试:
ApplicationContext auditorium =
new ClassPathXmlApplicationContext("ApplicationContextVer6.xml");
auditorium.getBean("Auditorium");
您无法观察销毁方法的工作情况,因为bean在Spring上下文中始终可用。当您关闭/销毁应用程序上下文时,应该销毁其中实例化的所有bean。查看
org.springframework.context.support.AbstractApplicationContext
类中的close()
和destroy()
方法。Grr,是的,那太完美了。把它写下来作为答案,我会投赞成票。这个例子来自《春天在行动》。(书中的虫子)
ApplicationContext auditorium =
new ClassPathXmlApplicationContext("ApplicationContextVer6.xml");
auditorium.getBean("Auditorium");
final ConfigurableApplicationContext auditorium =
new ClassPathXmlApplicationContext("ApplicationContextVer6.xml");
auditorium.getBean("Auditorium");
auditorium.close(); // thx Nathan
// auditorium.refresh() will also turn the lights off
// before turning them on again