【问题标题】:What is the correct way of handling exceptions in Spring Batch listeners?在 Spring Batch 侦听器中处理异常的正确方法是什么?
【发布时间】:2015-10-20 08:56:59
【问题描述】:

当使用 Spring Batch 中的 ItemWriteListener(或类似)时,处理侦听器委托引发的已检查异常的正确方法是什么?

例如:

public class MyClass implements ItemWriteListener<MyDTO> {
    // fields and constructor omitted

    @Override
    public void beforeWrite(List<MyDTO> items) {
        try {
            repository.loadAll(); // <-- Throws some checked exception
        } catch (Exception e) {
            // What to do here?
        }
    }
    // other methods omitted
}

我应该如何处理该异常?以下是一些想法:

  1. 重新抛出RuntimeException
  2. 记录异常并让步骤失败,这取决于此侦听器的操作
  3. MyDTO 项目上设置一些指示器以指示失败

当然,我不能抛出已检查的异常,因为它没有在ItemWriteListener接口上声明。

【问题讨论】:

  • 一个重要方面:您是否希望事务(和已处理的块)回滚? beforeWrite() 在整个块的事务中运行,因此“重新抛出”将导致回滚(参见 javadoc docs.spring.io/spring-batch/trunk/apidocs/org/springframework/…
  • @MichaelPralow 这正是我所需要的,因为这里的异常表明进程的状态无效。

标签: java spring listener spring-batch


【解决方案1】:

如果读取器/写入器依赖此操作,则引发运行时异常。这样,您可以确保 SpringBatch 正确处理事务和 SpringBatch db-tables 的更新。

【讨论】:

    猜你喜欢
    • 2012-03-29
    • 2019-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多