How can (can) at the end of the program call the destroy-method without calling appContext.close() ?

 void main(){ appContext = new ClassPathXmlApplicationContext("spring.xml"); ... blablabla... // завершаю программу без вызова appContext.close() } 

    2 answers 2

    You can register Shutdown Hook .

     void main(){ appContext = new ClassPathXmlApplicationContext("spring.xml"); appContext.registerShutdownHook(); ... blablabla... // завершаю программу без вызова appContext.close() } 

    In this case, Spring will register an application termination interceptor, in which the closing of the context will be called if it has not been called before. Convenient when there are several exit points from the application.

      The destroy-method will be executed for singleton bins only when the context is closed, for prototype it will not be executed at all since the context will not follow its life cycle

      • the question is how to execute without calling the context close - Senior Pomidor
      • I do not pretend to be true, but it seems to me in no way, since the singletons are created once, and stored in context, if you call the destroi method, respectively, it will end the bin's life cycle. What should come when you re-request bin - Uladzislau Kaminski
      • one
        @UladzislauKaminski if the context close() method is called, then if you attempt any operations with it (the context), after closing, for example, receiving a bin, java.lang.IllegalStateException will be thrown. - GreyGoblin