【问题标题】:I want to pass data from step one to the reader of step 2我想将数据从第一步传递给第二步的读者
【发布时间】:2020-02-13 14:59:04
【问题描述】:

我使用 Spring Batch 来完成以下工作流程:

  • 第 1 步:读取一个大的 CSV 并将其放入 Map
  • 第 2 步:从上一张地图中,我必须做一个业务逻辑。

我创建了一个名为 CourseCsvRepository 的 bean,以便将映射的 csv 保存到此映射(Singleton bean):

@Component
public class CourseCsvRepository {

    private Map<String, List<Course>> courseMappedByKey = new HashMap<>();


    public void addToMap(Course course){

        String key = "";
        key= key.concat(String.valueOf(course.getCodeStifLigne())).concat(course.getAntenne()).concat(String.valueOf(course.getIdtm())).concat(String.valueOf(course.getIdmiss())).concat(String.valueOf(course.getCourse())).concat(course.getNommiss());

        if(courseMappedByKey.containsKey(key)){
            courseMappedByKey.get(key).add(course);
        }else {
            final ArrayList<Course> list = new ArrayList<>();
            list.add(course);
            courseMappedByKey.put(key, list);
        }
    }

    public Map<String, List<Course>> getMap(){
        return this.courseMappedByKey;
    }

    public List<Course> getByKey(String key){
        return this.courseMappedByKey.get(key);
    }


}

我的第二个读者(第 2 步)如下:

@Bean
public ItemReader<List<Course>> readFromMap(){

    ListItemReader<List<Course>> reader = new ListItemReader<List<Course>>(new ArrayList(courseCsvRepository.getMap().values()));

    return reader;
}

但总是 courseCsvRepository.getMap() 返回 null,因为我的 bean 是在我执行第 1 步之前创建的(用于填充我们的地图)

@Bean
public Job writeCsvToDbJob() {
    return jobBuilderFactory.get("writeCsvToDbJob")
            .incrementer(new RunIdIncrementer())
            .start(step1())
            .next(step2())
            .build();
}

【问题讨论】:

    标签: java spring spring-batch


    【解决方案1】:

    想和大家分享上一个问题的答案:

    我的 bean 需要在步骤范围内,以便它们能够在每一步接收 stepExecutionContext 参数。如果它们没有步骤范围,它们的 bean 将在最初创建,并且不会在步骤级别接受填充的映射。

    @StepScope:How Does Spring Batch Step Scope Work

    @Bean
    @StepScope
    public ItemReader<List<Course>> readFromMap(){
    
        ListItemReader<List<Course>> reader = new ListItemReader<List<Course>>(new ArrayList(courseCsvRepository.getMap().values()));
    
        return reader;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 2020-12-25
      • 2022-01-21
      • 2022-01-14
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      相关资源
      最近更新 更多