2014-11-08 90 views
2

我有以下代码:Spring应用程序不会退出

public class TutorialSender { 

    public static void main(String[] args) throws Exception { 
     ApplicationContext context = new ClassPathXmlApplicationContext("rabbit-sender-context.xml");//loading beans 
     AmqpTemplate aTemplate = (AmqpTemplate) context.getBean("tutorialTemplate");// getting a reference to the sender bean 
     JSONObject obj = new JSONObject(); 
     obj.put("messageType", "ETL:ToFile"); 

     for (int i = 0; i < 100; i++) { 
      aTemplate.convertAndSend("ETLQueue",obj.toString());// send 
      // aTemplate.convertAndSend("Message # " + i + " on " + new Date());// send 
     } 

     System.out.println("send is done"); 
    } 

} 

然后我运行应用程序,它运行到最后一行,我可以看到“发送完成”被打印出来,但应用程序没有按退出。是因为春天阻止它退出吗?我该如何退出?

更新:我们不能使用context.close()直接既然有如此接近()函数,而不是需要使用以下

((ClassPathXmlApplicationContext) context).close(); 
+0

而不是铸造,只是为你的'上下文'变量使用更具体的类型。 – chrylis 2014-11-08 07:41:35

回答

2

Spring应用程序上下文保持打开状态,所以即使您的主线程结束,其他线程仍然可用且可运行。用context.close()关闭上下文,将事情干净地关闭。

此外,考虑将来的程序使用Spring Boot。您仍然需要主动关闭上下文以自动终止程序,但设置更容易一些。

-2

这可能是因为春天有一些线程中运行还没有被关闭你的时间main方法完成。调用System.exit(0)将退出程序。

+1

使用'System.exit'是一个非常钝的工具,无法替代理解发生了什么 – chrylis 2014-11-08 04:21:24