我正在使用Spring Batch设置作业服务器。我的JdbcCursorItemReader需要使用sql进行配置,这个sql会在每个作业运行的基础上进行更改。由于sql的变化,我希望读者拥有@StepScope,因此我不需要担心sql的状态。如何使用基于java的配置来配置Spring批处理StepScope?
所以我设置的一类这样的:
public class ParameterSettingJdbcCursorItemReader extends JdbcCursorItemReader implements StepExecutionListener {
@Override
public void beforeStep(StepExecution stepExecution) {
JobParameters jobParameters = stepExecution.getJobParameters();
if (jobParameters != null) {
List<Object> args = new ArrayList<Object>();
for (JobParameter jobParameter : jobParameters.getParameters().values()) {
args.add(jobParameter.getValue());
}
Object[] arrayArgs = args.toArray(new Object[args.size()]);
String sql = String.format(getSql(), arrayArgs);
setSql(sql);
}
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}
的想法是,我通过JobParameters传递SQL参数对象和使用的String.format填写动态变化的SQL。
我在整个服务器中使用基于Java的配置。我对我的ItemReader的一个实例豆的样子:
@Bean
@StepScope
public ItemReader<MyInputObject> myInputObjectItemReader() {
ParameterSettingJdbcCursorItemReader itemReader = new ParameterSettingJdbcCursorItemReader();
itemReader.setDataSource(myDataSource());
itemReader.setSql("SELECT * FROM my_table WHERE date = '%1$s'");
itemReader.setRowMapper(myInputObjectMapper);
return itemReader;
}
当我启动我的服务器和运行Spring Batch的工作,我得到这个错误:java.lang.IllegalStateException: No Scope registered for scope 'step'
我在其他地方看,为了能够使用StepScope,需要先将其添加到xml应用配置中,如下所示: <bean class="org.springframework.batch.core.scope.StepScope" />
但是由于我使用的是基于Java的配置,因此这不是一个选项。
那么,如何通过基于Java的配置注册StepScope?我已经试过这样:
@Bean
public org.springframework.batch.core.scope.StepScope stepScope() {
return new org.springframework.batch.core.scope.StepScope();
}
...但是当我做我上有没有关系StepScope豆类应用程序在启动过程中获取各种NPE上的。
在此先感谢。
[This](https://github.com/codecentric/spring-batch-javaconfig/blob/master/src/test/java/de/codecentric/batch /FlatfileToDbWithParametersAutowiringJobTests.java)似乎与您要做的相似。作者写了一个[blog](https://blog.codecentric.de/en/2013/06/spring-batch-2-2-javaconfig-part-2-jobparameters-executioncontext-and-stepscope/)来解释。 – Alex