Search code examples
springmethodsinitdestroy

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="turnOnLights" 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


Solution

  • 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