繁体   English   中英

如何关闭 spring ApplicationContext?

[英]How to close a spring ApplicationContext?

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

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

((ConfigurableApplicationContext)appCtx).close();

您需要向 JVM 注册一个关闭钩子,如下所示:

((AbstractApplicationContext)appCtx).registerShutdownHook();

有关更多信息,请参阅: Spring 手册:3.6.1.6 在非 Web 应用程序中优雅地关闭 Spring IoC 容器

如果您像下面这样初始化上下文

ApplicationContext context = new ClassPathXmlApplicationContext(beansXML); 

像这样干净的上下文

((ClassPathXmlApplicationContext) context).close();

如果 Java SE 7 及更高版本,请不要关闭,请使用 try-with-resources 以确保在语句结束时关闭每个资源。

try(final AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath*:META-INF/spring/*.xml" }))
{
     //write your code
}

关闭ApplicationContext对象的步骤

  1. ApplicationContext对象类型转换为ConfigurableApplicationContext对象。
  2. 然后调用 close 对象。

例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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