如何关闭一个春季应用程序上下文?

在应用程序完成之后,我想关闭 Spring 上下文。
相关代码有一个 ApplicationContext引用,但我找不到一个 close方法。

94285 次浏览

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

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

Even a more simpler way of doing this is using the abstract implementation of the ApplicationContextinterface.

 AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");


context.close();