【问题标题】:How to get JobParameter and JobExecutionContext in the ItemWriter?如何在 ItemWriter 中获取 JobParameter 和 JobExecutionContext?
【发布时间】:2013-02-03 16:35:31
【问题描述】:

我想在我的 ItemWriter 类中检索 JobParameterJobExecutionContext 对象。 如何进行?

我尝试实现StepExecutionListener,通过它我只是调用父类方法。但它没有成功。

提前致谢。

【问题讨论】:

  • 我通过扩展 StepExecutionListenerSupport 类解决了上述问题。之后覆盖父类方法即'beforeStep' public void beforeStep(StepExecution stepExecution) { // TODO 自动生成的方法存根 this.stepExecution =分步执行; }
  • 我遇到了同样的问题,并通过扩展 StepExecutionListenerSupport 类尝试了您的解决方案,并且未调用 afterStep 和 beforeStep 方法。您的 ItemWriter 是 StepScoped Bean 吗?当我的 ItemWriter 是 stepscoped bean 时,我遇到了同样的问题。在改回单例 bean 时,调用了 beforeStep 和 after 方法。
  • 如果您的要求是将编写器作为 StepExecutionListener 和 stepScoped,这就是解决方案.. 这对我有用。 stackoverflow.com/a/21941127/3004747

标签: java spring-batch


【解决方案1】:

实现 StepExecutionListener 是一种方法。事实上,这是 Spring Batch 1.x 中的唯一方法。

从 Spring Batch 2 开始,您有另一个选择:您可以将 Job Parameters 和 Job Execution Context 中的任何条目注入到您的项目编写器中。使用step 范围创建您的项目编写器,然后使用#{jobParameters['theKeyYouWant']}#{jobExecutionContext['someOtherKey']} 等表达式为您的项目编写器注入价值。

【讨论】:

  • Adrian,你能澄清一下这是将 JobExecutionContext 注入项目读取器、写入器或处理器的正确方法吗:1)在配置中,注入 bean:,则 2) 在 bean 中:private JobExecutionContext context; (不需要@Value)有什么遗漏或错误吗?非常感谢
  • 1.你需要 bean 是 step 范围,2. 你需要 setter 来设置“context”属性。
  • 一次执行多个作业时表现如何?任何线程安全问题?
  • Step 范围将为每个 step 执行创建一个新实例。
  • 使我的 itemWriter StepScope 产生空指针异常
【解决方案2】:

使用@BeforeStep注解在单步处理前调用方法。

//From the StepExecution get the current running JobExecution object.
public class MyDataProcessor implements ItemProcessor<MyDataRow, MyDataRow> {
    private JobExecution jobExecution;

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        jobExecution = stepExecution.getJobExecution();
    }
}

【讨论】:

    【解决方案3】:

    补充Adrian Shum的回答,如果你想避免每个作业参数被注入为类属性,你可以直接注入JobParameters的Map,如下:

    @Value("#{jobParameters}")
    private Map<String, JobParameter> jobParameters;
    

    【讨论】:

      【解决方案4】:

      如果您使用的是 Spring 配置文件,您可以通过以下方式访问 StepExecution 对象:

      <bean id="aaaReader" class="com.AAAReader" scope="step">
          <property name="stepExecution" value="#{stepExecution}" />
      </bean>
      

      在 AAAReader 类中,您需要创建正确的字段和 setter:

      private StepExecution stepExecution;
      
      public void setStepExecution(final StepExecution stepExecution) {
          this.stepExecution = stepExecution;
      }
      

      处理器和写入器类相同。

      【讨论】:

      • 想知道为什么我对此投了反对票 - 没有评论?
      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 2022-01-22
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多