春季批。使用jobExecutionContext中的参数创建ItemReader bean

时间:2019-11-07 11:52:26

标签: java spring spring-batch

我需要使用在BeforeStep侦听器中定义的参数创建itemReader bean。这是必需的,因为我需要设置SQL和SQL参数值。 运行我的应用程序后,我遇到异常:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.mappingReaderConfig': Scope 'step' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope

如何避免重写代码? 这是我的bean的示例:

@Configuration
@StepScope
public class MappingReaderConfig {

private final DataSource ds;

@Autowired
public MappingReaderConfig(DataSource ds) {
    this.ds = ds;
}

@Value("#{jobParameters['START_DATE']}")
private String startDate;

@Value("#{jobParameters['END_DATE']}")
private String endDate;

@Value("#{jobExecutionContext['myProcessData']}")
private MyProcessData myProcessData;

@Value("#{jobParameters['PROCESS_ID']}")
private Long processId;

@Bean
@SuppressWarnings("unchecked")
public ItemReader<MapRowByMap> mappingItemReader() {
    return new JdbcCursorItemReaderBuilder<>()
            .dataSource(ds)
            .sql(myProcessData.getCursor())
            .verifyCursorPosition(true)
            .preparedStatementSetter(ps -> {
                ps.setDate(1, Date.valueOf(LocalDate.parse(startDate)));
                ps.setDate(2, Date.valueOf(LocalDate.parse(endDate)));
            })
            .rowMapper((RowMapper) (rs, rowNum) -> {
                MapRowByMap res = new MapRowByMap();
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                for(int i=1; i<=columns; ++i) {
                    MapColumn mapColumn = new MapColumn(md.getColumnName(i), rs.getObject(i));
                    res.getRowColumns().put(md.getColumnName(i),mapColumn);
                }
                return res;
            }).name(processId.toString()).build();
}
}

0 个答案:

没有答案