Spring Batch - @ BeforeStep未在分区程序中调用

我们正在尝试使用spring batch partitioning来实现批处理作业 . 在“步骤2”这是一个分区步骤,我需要步骤1中的一些数据进行处理 . 我使用了StepExecutionContext,它将在步骤1被提升为作业执行上下文来存储这个数据 .

我尝试在分区器类中使用@BeforeStep注释来获取stepExecutionContext,我可以从中提取先前存储的数据并将其放入分区器的ExecutionContext中 . 但是,在分区器中不会调用带@BeforeStep注释的方法 .

有没有其他方法来实现这一目标 .

分区程序实现

public class NtfnPartitioner implements Partitioner {

    private int index = 0;
    String prev_job_time  = null;
    String curr_job_time  = null;

    private StepExecution stepExecution ;
    ExecutionContext executionContext ;

    @Override
    public Map<String, ExecutionContext> partition(int gridSize)
    {

           System.out.println("Entered Partitioner");
           List<Integer> referencIds = new ArrayList<Integer>();
           for (int i = 0; i < gridSize;i++) {
            referencIds.add(index++);
           }
           Map<String, ExecutionContext> results = new LinkedHashMap<String,ExecutionContext>();
          for (int referencId : referencIds) {
            ExecutionContext context = new ExecutionContext();
            context.put("referenceId", referencId);
            context.put(NtfnConstants.PREVIOUS_JOB_TIME, prev_job_time);
            context.put(NtfnConstants.JOB_START_TIME, curr_job_time);
            results.put("partition." + referencId, context);
          }
            return results;
        }

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        // TODO Auto-generated method stub
          System.out.println("Entered Before step in partion");
          JobExecution jobExecution = stepExecution.getJobExecution();
          ExecutionContext jobContext = jobExecution.getExecutionContext();
          System.out.println("ExecutionContext"+jobContext);
          String prev_job_time  = (String) jobContext.get(NtfnConstants.PREVIOUS_JOB_TIME);
          String curr_job_time  = (String) jobContext.get(NtfnConstants.JOB_START_TIME);


    }

回答(1)

2 years ago

bean应该是步骤范围的 .

Java,注释类:

@StepScope

XML,在bean定义中:

scope="step"

另请查看关于代理bean的answer(不确定这是否适用于您,因为没有提供除分区器之外的其他代码) . 在这种情况下,您仍然可以在步骤构建期间显式地将分区器添加为侦听器:

@Autowired
private NtfnPartitioner partitioner;    

...

final Step masterStep = stepBuilderFactory.get("master")
                    .listener(partitioner)
                    .partitioner("slave", partitioner)
                    .step(slave)
                    ...

或者,如果您的分区器不是bean(例如,您是基于动态的东西创建它),您仍然可以将其添加为侦听器:

final NtfnPartitioner partitioner = new NtfnPartitioner();    
final Step masterStep = stepBuilderFactory.get("master")
                    .listener(partitioner)
                    .partitioner("slave", partitioner)
                    .step(slave)
                    ...