步驟監聽器
@Component
public class StepListener implements StepExecutionListener {private StepExecution stepExecution;public StepExecution getStepExecution() {return this.stepExecution;}@Overridepublic void beforeStep(StepExecution stepExecution) {this.stepExecution = stepExecution;}@Overridepublic ExitStatus afterStep(StepExecution stepExecution) {return null;}
}
讀
@Component
@StepScope
public class ProductItemReader implements ItemReader<Product> {private Iterator<Product> iterator;private final StepListener stepListener;private final XxxRepository xxxRepository;public ProductItemReader(StepListener stepListener,XxxRepository xxxRepository) {this.stepListener = stepListener;this.xxxRepository = xxxRepository;}@Overridepublic Product read() {// 利用repository讀取數據this.iterator = xxxRepository.xxx();// StepExecution 在 Step 執行時才可用,必須懶初始化StepExecution stepExecution = stepListener.getStepExecution();ExecutionContext executionContext = stepExecution.getExecutionContext();// 可設置STEP內上下文return iterator.hasNext() ? iterator.next() : null;}
}
處理
@Slf4j
@StepScope
@Component("productProcessor")
public class ProductProcessor implements ItemProcessor<Product, Product> {private final StepListener stepListener;public ProductProcessor(@Qualifier("stepListener") StepListener stepListener) {this.stepListener = stepListener;}@Overridepublic Product process(Product product) {// 從步驟域內讀取數據或設置數據StepExecution stepExecution = productStepListener.getStepExecution();ExecutionContext executionContext = stepExecution.getExecutionContext();return product;}}
寫
@Slf4j
@Component("productWriter")
public class ProductWriter implements ItemWriter<Product> {private final XxxRepository repository;private final StepListener stepListener;public ProductWriter(@Qualifier(value = "productRepository") XxxRepository xxxRepository,@Qualifier(value = "stepListener") StepListener stepListener) {this.repository = xxxRepository;this.stepListener = stepListener;}@Overridepublic void write(List<? extends Product> items){StepExecution stepExecution = this.stepListener.getStepExecution();ExecutionContext executionContext = stepExecution.getExecutionContext();items.forEach( product -> {...});}
}
定義步驟
@Bean
public Step printStep(){TaskletStep taskletStep = stepBuilderFactory.get("testStep").listener(stepListener).<Product, Product>chunk(10).reader(productItemReader).processor(productProcessor).writer(productWriter).build();return taskletStep;
}
使用步驟
@Bean
public Job testJob(){return jobBuilderFactory.get("productJob").start(printStep())....build();
}