Aubergine
Aubergine

Reputation: 6052

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

Upvotes: 2

Views: 1276

Answers (2)

omnomnom
omnomnom

Reputation: 9149

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.

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299218

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

Upvotes: 5

Related Questions