How to close a spring ApplicationContext?

JavaSpring

Java 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

  1. Type Cast the ApplicationContext Object to ConfigurableApplicationContext object.
  2. 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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAvner LevyView Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - JavadogbaneView Answer on Stackoverflow
Solution 3 - JavaAshish GaikwadView Answer on Stackoverflow
Solution 4 - JavaChiragView Answer on Stackoverflow
Solution 5 - Javapushpendra yadavView Answer on Stackoverflow
Solution 6 - JavaMeenakshi SinghView Answer on Stackoverflow
Solution 7 - JavaLernord macView Answer on Stackoverflow