首页 文章

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

提问于
浏览
2

我最初在[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时传递作业参数,因为它正在抛出

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

我的配置就像

@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

    这是您传递作业参数的方法

    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();
    }
    

相关问题