2

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?

1 Answer 1

2

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
  • but the destroy-method wasn't called even the process terminated. Aug 14, 2012 at 8:58
  • @amwaiman1988: it will be called by the application container when it shuts down. Since your code creates the application context via new, it doesn't seem to be running inside an application container at all. That means it's not really Spring code. If it's in a book, maybe it's just meant to illustrate the concepts, not to be actually executed. Aug 14, 2012 at 9:17
  • @lamwaiman1988: the book seems to have pretty bad reviews on Amazon... Aug 14, 2012 at 9:19
  • I am having a nice time with it although I have only read about 1/10 of it. The examples are interesting comparing to other book which are boring to hell. It's okay for beginner. Aug 14, 2012 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.