如何在Spring批处理中创建动态步骤

如何在Spring批处理中创建动态步骤,spring,spring-batch,Spring,Spring Batch,我需要创建“N”个步骤,这取决于从数据库接收的“maxHierLevel”值,并按顺序执行- int maxHierLevel = testService.getHighestLevel(); Step masterCalculationStep = stepBuilderFactory.get("CALCUL_STEP_1") .<Map<Long, List<CostCalculation>>, List<TempCostCalc>

我需要创建“N”个步骤,这取决于从数据库接收的“maxHierLevel”值,并按顺序执行-

int maxHierLevel = testService.getHighestLevel(); 

Step masterCalculationStep = stepBuilderFactory.get("CALCUL_STEP_1")
        .<Map<Long, List<CostCalculation>>, List<TempCostCalc>>chunk(1)
        .reader(reader)
        .processor(processor)
        .writer(writer)
        .build();

final Step[] stepsArray = new Step[maxHierLevel];

for (int i = 0; i < stepsArray.length; i++) {
    stepsArray [i] = stepBuilderFactory.get("processingRecordsInLevel_"+i)
            .partitioner("partitionningSlavStep_"+i , calculationPartioner(i))
            .step(masterCalculationStep)
            .listener(new StepResultListener())
            .taskExecutor(taskExecutor)
            .build();
}

return jobBuilderFactory.get("mainCalculationJob")
                .incrementer(new RunIdIncrementer())
                .flow(truncTableTaskletStep())
                .next(loadPlantList)
                .next(stepsArray[0]) 
                .next(stepsArray[1])
                .next(stepsArray[2])
                .end()
                .listener(listener)
                .build();

我们是否可以动态添加步骤,如nextstepsArray[0]并返回作业引用?

是的,您可以动态创建步骤并返回作业引用。以下是在您的案例中如何做到这一点的示例:

@Bean
public Job job() {
    Step[] stepsArray = // create your steps array or pass it as a parameter
    SimpleJobBuilder jobBuilder = jobBuilderFactory.get("mainCalculationJob")
            .incrementer(new RunIdIncrementer())
            .start(truncTableTaskletStep());
    for (Step step : stepsArray) {
        jobBuilder.next(step);
    }
    return jobBuilder.build();
}

希望这能有所帮助。

您知道如何使这些步骤具有上下文意识吗。例如,他们可以使用@BeforeStep annotation?@MahmoudBenHassine感谢您证明了将步骤动态添加到批处理作业的解决方案,我有额外的用例并行运行任何输入都可以吗?