【问题标题】:Spring batch - org.springframework.batch.item.ReaderNotOpenException - jdbccursoritemreader春季批处理 - org.springframework.batch.item.ReaderNotOpenException - jdbccursoritemreader
【发布时间】:2021-06-21 09:56:42
【问题描述】:

在项目阅读器实现中尝试读取 JdbcCursorItemReader 时,我得到阅读器未打开异常。我检查了堆栈溢出,但无法讨论 jdbc 项目阅读器。

这里是批量配置和项目阅读器实现的代码。仅添加了必需的代码。

    public class BatchConfig extends DefaultBatchConfigurer {
@Bean
public ItemReader<Allocation> allocationReader() {
return new AllocationReader(dataSource);
}
@Bean
public Step step() {
return stepBuilderFactory.get("step").<Allocation, Allocation>chunk (1).reader(allocationReader()).processor(allocationProcessor()).writer(allocationWriter()).build();
}
}




    public class AllocationReader implements ItemReader<Allocation> {
private DataSource ds;
private string block;
public AllocationReader(DataSource ds) {
this.ds = ds;
}
@BeforeStep
public void readStep(StepExecution StepExecution) {
this.stepExecution = StepExecution;
block = StepExecution.getJobExecution().get ExecutionContext().get("blocks");
}
@Override
public Allocation read() {
JdbcCursorItemReader<Allocation> reader = new JdbcCursorItemReader<Allocation>();
reader.setSql("select * from blocks where block_ref = + block);
reader.setDataSource(this.ds);
reader.setRowMapper(new AllocationMapper());
return reader.read();
}}

我无法在批处理配置中将项目阅读器编写为 bean,因为我需要在进入项目阅读器以访问 stepexecution 之前调用。

如果Item reader read()函数返回类型更改为jdbccursorItemReader类型,会在Step reader()中抛出类型异常。

让我知道我缺少什么或需要任何其他代码 sn-p。

【问题讨论】:

    标签: spring-boot spring-batch spring-jdbc itemrenderer


    【解决方案1】:

    您正在AllocationReaderread 方法中创建一个JdbcCursorItemReader 实例。这是不正确的。此方法的代码应该是实际read操作的实现,而不是用于创建项目阅读器。

    我无法在批处理配置中将项目阅读器编写为 bean,因为我需要在进入项目阅读器的步骤之前调用以访问步骤执行。

    对于这个用例,您可以将阅读器定义为步进范围的 bean,并根据需要从作业执行上下文中注入属性。这在此处的参考文档中进行了解释:Late Binding of Job and Step Attributes。在您的情况下,读者可以这样定义:

    @Bean
    @StepScoped
    public JdbcCursorItemReader<Allocation> itemReader(@Value("#{jobExecutionContext['block']}") String block) {
       // use "block" as needed to define the reader
       JdbcCursorItemReader<Allocation> reader = new JdbcCursorItemReader<Allocation>();
       reader.setSql("select * from blocks where block_ref = " + block);
       reader.setDataSource(this.ds);
       reader.setRowMapper(new AllocationMapper());
       return reader;
    }
    

    当你定义一个ItemStream的item reader bean时,你需要让bean定义方法至少返回ItemStreamReader(或者实际的实现类型),这样Spring Batch才能正确地定义bean的作用域并调用@ 987654329@ 在该步骤中适当。否则,open 方法将不会被调用,因此您将得到 ReaderNotOpenException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-15
      • 2018-05-27
      • 2015-05-13
      • 2017-06-25
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      相关资源
      最近更新 更多