How to close a spring ApplicationContext?

After my application finishes I want to close the spring context.
The relevant code has an ApplicationContext reference but I couldn't find a close method.


Solution 1:

Downcast your ApplicationContext to ConfigurableApplicationContext which defines close() method:

((ConfigurableApplicationContext)appCtx).close();

Solution 2:

You need to register a shutdown hook with the JVM as shown below:

((AbstractApplicationContext)appCtx).registerShutdownHook();

For more information see: Spring Manual: 3.6.1.6 Shutting down the Spring IoC container gracefully in non-web applications