小编典典

将JobParameters和ExecutionContext传递给@Bean Tasklet?

spring-boot

我正在将基于Spring Batch XML的应用程序转换为Spring
Boot批注。在我的XML文件中,我不确定如何将那些jobParameters和执行上下文传递给tasklet?

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:batch="http://www.springframework.org/schema/batch" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task  http://www.springframework.org/schema/task/spring-task.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <batch:job id="job1">
        <batch:step id="contextStep" >
            <batch:tasklet ref="contextTasklet" />
        </batch:step>
    </batch:job>

    <bean id="contextTasklet" class="com.XXX.batch.tasklet.ContextTasklet" scope="step">
        <property name="runMode" value="#{jobParameters['runMode']}" />
        <property name="executionContext" value="#{stepExecution.jobExecution.executionContext}" />
    </bean>
</beans>

ContextTasklet.java

@Data
@Configuration
@StepScope
public class ContextTasklet implements Tasklet{

    private String runMode;
    private ExecutionContext executionContext;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("mode",
                runMode);

        return RepeatStatus.FINISHED;
    }
}

阅读 415

收藏
2020-05-30

共1个答案

小编典典

您可以使用@Value注释注入作业参数和执行上下文值:

@Data
@Configuration
@StepScope
public class ContextTasklet implements Tasklet{

   @Value("#{jobParameters['runMode']}")
   private String runMode;

   @Value("#{stepExecution.jobExecution.executionContext}")
   private ExecutionContext executionContext;

   @Override
   public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
       chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("mode",
            runMode);

       return RepeatStatus.FINISHED;
    }
}
2020-05-30