How to close a spring ApplicationContext?
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
If Java SE 7 and later, don't close, use try-with-resources which ensures that each resource is closed at the end of the statement.
try(final AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath*:META-INF/spring/*.xml" }))
{
//write your code
}
If you initialise context like one below
ApplicationContext context = new ClassPathXmlApplicationContext(beansXML);
clean context like these
((ClassPathXmlApplicationContext) context).close();
Downcast your ApplicationContext
to ConfigurableApplicationContext
which defines close()
method:
((ConfigurableApplicationContext)appCtx).close();