简体   繁体   中英

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.

将您的ApplicationContext向下转换为ConfigurableApplicationContext ,它定义了close()方法:

((ConfigurableApplicationContext)appCtx).close();

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 you initialise context like one below

ApplicationContext context = new ClassPathXmlApplicationContext(beansXML); 

clean context like these

((ClassPathXmlApplicationContext) context).close();

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
}

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();
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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM