87

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

4

7 回答 7

153

向下转换你ApplicationContextConfigurableApplicationContext定义close()方法:

((ConfigurableApplicationContext)appCtx).close();
于 2013-01-20T11:27:07.157 回答
36

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

((AbstractApplicationContext)appCtx).registerShutdownHook();

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

于 2013-03-26T12:42:54.160 回答
14

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

ApplicationContext context = new ClassPathXmlApplicationContext(beansXML); 

像这样干净的上下文

((ClassPathXmlApplicationContext) context).close();
于 2016-05-23T12:42:17.443 回答
12

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

try(final AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath*:META-INF/spring/*.xml" }))
{
     //write your code
}
于 2017-01-13T19:06:22.667 回答
1

关闭ApplicationContext对象的步骤

  1. 键入将ApplicationContext对象转换为ConfigurableApplicationContext对象。
  2. 然后调用关闭对象。

例子:

 ApplicationContext context = new ClassPathXmlApplicationContext("mybeans.xml");

((ConfigurableApplicationContext)context ).close();
于 2017-11-09T13:04:06.763 回答
1
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();
于 2019-11-25T06:28:35.960 回答
0

甚至更简单的方法是使用ApplicationContextinterface.

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

context.close();
于 2021-09-08T13:29:07.293 回答