In am reading Spring in Action (3rd edition) and here a snippet from it:
ApplicationContext ctx=new ClassPathXmlApplicationContext("springidol.xml");
Performer performer=(Performer)ctx.getBean("poeticDuke");
performer.perform();
It doesn’t has any problem,however, when the author introduce the init-method and destroy-method:
<bean id="poeticDuke"
class="com.springinaction.springidol.PoeticJuggler"
init-method="turnOnLights"
destroy-method="turnOffLights">
Somehow the output only got the init-method but not the destroy-method. Then I realized that the context call destroy-method upon its close and I tried to code as following:
ApplicationContext ctx=new ClassPathXmlApplicationContext("springidol.xml");
Performer performer=(Performer)ctx.getBean("poeticDuke");
performer.perform();
ctx.close();
It doesn’t compile because the interface ApplicationContext doesn’t have the method close. It only work as following:
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("springidol.xml");
Performer performer=(Performer)ctx.getBean("poeticDuke");
performer.perform();
ctx.close();
Why did the author wrote it that way?
The init and destroy methods are called by the Spring application container. Application code should never call them, and since the ApplicationContext
interface is meant to be used by applications, it does not contain the method.
That’s the whole point of frameworks like Spring: “don’t call us, we will call you”.
Note that the close()
method is included in the ConfigurableApplicationContext
interface, which is the API for the application container to call.
4