首页 > 解决方案 > Spring批处理ApplicationContext

问题描述

我在我的项目中使用弹簧批处理应用程序。一旦我启动了 spring batch main 方法,在 main 方法结束时,我正在使用关闭 classpathxmlapplicationcontext。

  1. 是否需要关闭classpathxmlapplicationcontext?
  2. 主要问题之一是,如果我在批处理应用程序之间触发了任何异步调用,那么当主方法代码到达 classpathxmlapplicationcontext.close() 时,这些异步调用将被终止?
  3. 如果我评论了 classpathxmlapplicationcontext.close() 那么,即使所有逻辑都已完成,我的程序也会连续运行而没有任何终止。
  4. 如何解决这个问题?我需要在关闭我的 classpathxmlapplicationcontext 之前执行所有异步调用。
  5. 考虑到我所有的异步都需要一点多余的时间。

标签: javaasynchronousspring-batchapplicationcontext

解决方案


是的,我们必须关闭 classpathxmlapplicationcontext。

试试下面的代码

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(...);
try {
    [...]
} finally {
    ctx.close();
}

或者,在 Java 7 或之后

try(ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(...)) {
    [...]
}

推荐阅读