SpringBatch(8):利用StepExecutionListener传递Job参数

前言

Step在执行时,需要一些参数,如何给Step传递参数?

利用StepExecutionListener传递Job参数

package com.it2.springbootspringbatch01.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
@EnableBatchProcessing
@Slf4j
public class JobParamDemo implements StepExecutionListener {

    Map<String, JobParameter> parameterMap;

    @Override
    public void beforeStep(StepExecution stepExecution) {
        parameterMap= stepExecution.getJobParameters().getParameters();
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }

    //注入任务对象工厂
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    //任务的执行由Step决定,注入step对象的factory
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    //创建Job对象
    @Bean
    public Job jobDemo2() {
        return jobBuilderFactory.get("jobDemo2")
                .start(step11())
                .build();

    }

    //创建Step对象

    /**
     * Job执行的Step,Job传递的数据在step中使用
     * 如何给step传递数据?
     * 使用监听器,给step传递数据,实现StepExecutionListener
     * @return
     */
    @Bean
    public Step step11() {
        return stepBuilderFactory.get("step11")
                .listener(this)
                .tasklet(new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                log.info("------step11 ok");
                log.info("参数:"+parameterMap);
                return RepeatStatus.FINISHED;
            }
        }).build();
    }
}

StepExecutionListener 有两个方法before和after,我们可以使用before给step传递参数。
测试时,给args传递了name=xiaowang的参数,启动服务器
在这里插入图片描述
在这里插入图片描述


版权声明:本文为u011628753原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。