如何使用java配置创建spring bean时传递JobParameters

时间:2018-05-29 18:55:21

标签: spring spring-batch

我最初在[Getting "Scope 'step' is not active for the current thread" while creating spring batch beans处提出了一个问题,根据Spring batch scope issue while using spring boot提供的建议,我尝试替换@StepScope注释,而是在配置中定义了StepScope bean,如下所示

@Bean
@Qualifier("stepScope")
public org.springframework.batch.core.scope.StepScope stepScope() {

    final org.springframework.batch.core.scope.StepScope stepScope = new org.springframework.batch.core.scope.StepScope();
    stepScope.setAutoProxy(true);
    return stepScope;
}

通过此更改,我无法在创建bean时传递作业参数,因为它正在抛出

  

'jobParameters'在'org.springframework.beans.factory.config.BeanExpressionContext'类型的对象上找不到

我的配置就像

@Configuration
@EnableBatchProcessing
public class MyConfig{

@Bean
@Qualifier("partitionJob")
public Job partitionJob() throws Exception {

    return jobBuilderFactory
            .get("partitionJob")
            .incrementer(new RunIdIncrementer())
            .start(partitionStep(null))
             .build();
}

@Bean
@StepScope
public Step partitionStep(
        @Value("#{jobParameters[gridSize]}") String gridSize)
        throws Exception {

    return stepBuilderFactory
            .get("partitionStep")
            .partitioner("slaveStep", partitioner())
            .gridSize(gridZize)
            .step(slaveStep(chunkSize))
            .taskExecutor(threadPoolTaskExecutor()).build();
}

@Bean
@StepScope
public Step slaveStep(int chunkSize) throws Exception {

    return stepBuilderFactory
            .get("slaveStep")
            ......
            ........
}

如果需要像我的示例那样访问作业参数,我读到应该使用@StepScope注释bean。但是如上所述我得到了例外。

1 个答案:

答案 0 :(得分:0)

这是传递作业参数的方法

  GenericApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
    JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");     
        JobParameters jobParameters = new JobParametersBuilder()
                                                               .addString("paramter1", "Test")  
                                                               .toJobParameters();

        Job job = (Job) context.getBean("myJob");
        JobExecution execution = jobLauncher.run(job, jobParameters);

访问作业参数

    Bean
@StepScope
public Step partitionStep(
        @Value("#{jobParameters['paramter1']}") String gridSize)
        throws Exception {

    return stepBuilderFactory
            .get("partitionStep")
            .partitioner("slaveStep", partitioner())
            .gridSize(gridZize)
            .step(slaveStep(chunkSize))
            .taskExecutor(threadPoolTaskExecutor()).build();
}