How to close a spring ApplicationContext?
JavaSpringJava Problem Overview
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.
Java Solutions
Solution 1 - Java
Downcast your ApplicationContext
to ConfigurableApplicationContext
which defines close()
method:
((ConfigurableApplicationContext)appCtx).close();
Solution 2 - Java
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
Solution 3 - Java
If you initialise context like one below
ApplicationContext context = new ClassPathXmlApplicationContext(beansXML);
clean context like these
((ClassPathXmlApplicationContext) context).close();
Solution 4 - Java
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
}
Solution 5 - Java
Steps to close the ApplicationContext
Object
- Type Cast the
ApplicationContext
Object toConfigurableApplicationContext
object. - then call the close object on that.
example:
ApplicationContext context = new ClassPathXmlApplicationContext("mybeans.xml");
((ConfigurableApplicationContext)context ).close();
Solution 6 - Java
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("SpringCnf.xml");
Resturant rstro1=(Resturant)context.getBean("resturantBean");
rstro1.setWelcome("hello user");
rstro1.welcomeNote();
((ClassPathXmlApplicationContext) context).close();
Solution 7 - Java
Even a more simpler way of doing this is using the abstract implementation of the ApplicationContextinterface
.
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
context.close();