如何关闭Spring ApplicationContext?

时间:2013-01-20 11:23:17

标签: java spring

我的申请完成后,我想关闭春天的背景 相关代码有ApplicationContext引用,但我找不到close方法。

6 个答案:

答案 0 :(得分:132)

将您的ApplicationContext转发给定义ConfigurableApplicationContext方法的close()

((ConfigurableApplicationContext)appCtx).close();

答案 1 :(得分:34)

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

((AbstractApplicationContext)appCtx).registerShutdownHook();

有关详细信息,请参阅:Spring Manual: 3.6.1.6 Shutting down the Spring IoC container gracefully in non-web applications

答案 2 :(得分:11)

如果你初始化下面的上下文

ApplicationContext context = new ClassPathXmlApplicationContext(beansXML); 

像这些一样清理上下文

((ClassPathXmlApplicationContext) context).close();

答案 3 :(得分:10)

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

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

答案 4 :(得分:1)

关闭ApplicationContext对象

的步骤
  1. 键入将ApplicationContext对象转换为ConfigurableApplicationContext对象。
  2. 然后调用close对象。
  3. 示例:

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

答案 5 :(得分:0)

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