如何在 Spring Batch 中从 ItemReader 访问作业参数?

2024-07-04

这是我的一部分job.xml:

<job id="foo" job-repository="job-repository">
  <step id="bar">
    <tasklet transaction-manager="transaction-manager">
      <chunk commit-interval="1"
        reader="foo-reader" writer="foo-writer"
      />
    </tasklet>
  </step>
</job>

这是项目阅读器:

import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("foo-reader")
public final class MyReader implements ItemReader<MyData> {
  @Override
  public MyData read() throws Exception {
    //...
  }
  @Value("#{jobParameters['fileName']}")
  public void setFileName(final String name) {
    //...
  }
}

Spring Batch 在运行时是这么说的:

Field or property 'jobParameters' cannot be found on object of 
type 'org.springframework.beans.factory.config.BeanExpressionContext'

这是怎么回事?在哪里可以阅读有关 Spring 3.0 中这些机制的更多信息?


如前所述,您的读者需要处于“步骤”范围内。您可以通过以下方式完成此操作@Scope("step")注解。如果您将该注释添加到阅读器中,它应该对您有用,如下所示:

import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("foo-reader")
@Scope("step")
public final class MyReader implements ItemReader<MyData> {
  @Override
  public MyData read() throws Exception {
    //...
  }

  @Value("#{jobParameters['fileName']}")
  public void setFileName(final String name) {
    //...
  }
}

默认情况下此范围不可用,但如果您使用batchXML 命名空间。如果不是,请将以下内容添加到 Spring 配置中将使范围可用,按照Spring Batch 文档 http://static.springsource.org/spring-batch/reference/html/configureStep.html#step-scope:

<bean class="org.springframework.batch.core.scope.StepScope" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Spring Batch 中从 ItemReader 访问作业参数? 的相关文章

随机推荐