gpt4 book ai didi

java - 如何使用基于 Java 的配置来配置 Spring Batch StepScope?

转载 作者:搜寻专家 更新时间:2023-10-31 20:20:28 27 4
gpt4 key购买 nike

我正在使用 Spring Batch 设置作业服务器。我的 JdbcCursorItemReader 需要使用在每个作业运行时更改的 sql 配置。因为sql改变了,我希望读者有@StepScope这样我就不用担心sql状态。

所以我设置了这样一个类:

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 看起来像:

@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 无关的 bean 上的应用程序启动期间得到各种 NPE。

提前致谢。

最佳答案

您必须使用 ApplicationContext 注册范围。通常这会在您使用 @EnableBatchProcessing 时为您完成。你这样做了吗(将该注释添加到你的 @Configurations 之一)?

关于java - 如何使用基于 Java 的配置来配置 Spring Batch StepScope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22108315/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com