开发者

Spring init and destroy methods

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");
}  

}

For xml context I have:

 <bean id="Auditorium" class="com.idol.Auditorium" init-method="turnOnL开发者_如何转开发ights" destroy-method="turnOffLights"/>

Testing:

ApplicationContext auditorium =
        new ClassPathXmlApplicationContext("ApplicationContextVer6.xml"); 

auditorium.getBean("Auditorium");

I get:

Does only print "Lights are turned on" and doesn't print "Lights are turned off". I though that before destroying the bean it should invoke the destroy-method too, what am I missing or not getting? (I have no errors in log, just in case)

Thanks


Try it like this:

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


You cannot observe destroy method working, because beans are available in Spring context all the time. When you close/destroy your application context, then all beans instantiated within it should be destroyed. Take a look at the close() and destroy() methods at the org.springframework.context.support.AbstractApplicationContext class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜