【问题标题】:Spring batch run exception throwable method after each tasklet done in afterstep()在 afterstep() 中完成每个 tasklet 之后的 Spring 批处理运行异常抛出方法
【发布时间】:2021-09-07 10:47:00
【问题描述】:
public class TaskletConfiguration {

  ...

  @Bean
  public Step step() {
    return steps.get("step")
        .tasklet(tasklet)
        .exceptionHandler(logExceptionHandler()) // Handler for logging exception to specific channel
        .build();
  }

  @Bean
  public Job job() {
    return jobs.get("job")
        .start(step())
        .build();
  }
}

public class ExampleTasklet implements Tasklet, StepExecutionListener {

  ...

  @Override
  public RepeatStatus execute(...) throws Exception {
    // Do my tasklet
    // Throw if it fails, and be handled by logExceptionHandler()
  }

  @Override
  public ExitStatus afterStep(StepExecution stepExecution) {
    // Want to throw so that logExceptionHandler() can handle it as throwing in execute().
    throwable_function();
  }
}

这是我在 Spring Boot 中使用 tasklet 的示例代码。 我的问题是:我想从afterstep() 抛出异常,但是接口不允许。

尽管有这个限制,我为什么痴迷afterstep() 是因为我想制作抽象类来制作可以验证afterstep() 中的每个执行的Tasklet 模板。我希望在完成所有execute() 之后运行验证,这将被子类覆盖。所以我别无选择,只能使用afterstep()

在每个execute() 与 throwable 或afterstep() 之后运行验证方法的任何想法都可以将异常传递给logExceptionHandler()?我希望在TaskletConfiguration 类中定义logExceptionHandler()。如果在Tasklet类中定义的话会很胖,因为我会做抽象类,它会被很多子类继承。

【问题讨论】:

    标签: java exception spring-batch spring-batch-tasklet


    【解决方案1】:

    StepExecutionListener#afterStep 并非旨在引发检查异常。以下是其 Javadoc 的摘录:

    Called after execution of step's processing logic (both successful or failed).
    Throwing exception in this method has no effect, it will only be logged.
    

    此外,即使您在 afterStep 中抛出(运行时)异常,该异常也不会传递给异常处理程序,只会按照 Javadoc 中的说明记录。

    我认为在StepExecutionListener#afterStep 中抛出异常为时已晚,该方法可用于检查步骤执行的状态并在需要时修改 ExitStatus 以驱动其余的作业执行流程。

    【讨论】:

    • 我理解你的意思是afterStep 不是为检查异常而设计的。谢谢。那么,如何让抽象类的所有子类最后都调用同一个方法(文中的验证方法)呢?
    • 您希望使用StepExecutionListener#afterStep 中的异常处理程序,但如前所述,这不起作用。所以afterStep 不适合你。你可以在你的 tasklet 中添加一个受保护的方法并在 execute 中调用它。然后子类只能覆盖该方法。
    猜你喜欢
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 2016-12-21
    • 1970-01-01
    • 2014-07-08
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多