JavaSpring应用程序没有退出
我有以下代码:
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()
,因为有这么多close()函数,所以需要使用以下函数
((ClassPathXmlApplicationContext) context).close();
# 1 楼答案
Spring应用程序上下文保持打开状态,因此即使主线程已结束,其他线程仍然可用且可运行。用
context.close()
关闭上下文以彻底关闭另外,考虑使用Spring启动程序。您仍然需要主动关闭上下文以自动终止程序,但安装会简单一些