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");
}
}
对于xml上下文,我有:
<bean id="Auditorium" class="com.idol.Auditorium" init-method="turnOnLights" destroy-method="turnOffLights"/>
测试:
ApplicationContext auditorium =
new ClassPathXmlApplicationContext("ApplicationContextVer6.xml");
auditorium.getBean("Auditorium");
我明白了:
仅打印“灯已打开”且不打印“灯已关闭”。我虽然在破坏bean之前它也应该调用destroy-method,但我错过了什么或没有得到什么? (我在日志中没有错误,以防万一)
由于
答案 0 :(得分:5)
试试这样:
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
答案 1 :(得分:0)
您无法观察destroy方法的工作原理,因为bean始终在Spring上下文中可用。当您关闭/销毁应用程序上下文时,应该销毁在其中实例化的所有bean。请查看close()
课程中的destroy()
和org.springframework.context.support.AbstractApplicationContext
方法。