首页 > 解决方案 > Spring Batch 未执行 StepExecutionListener beforeStep 或 afterStep 方法

问题描述

更新:我正在重新运行我的代码,实际上注意到我的听众都没有真正工作......

我有一个 Spring Batch 应用程序,我正在覆盖 StepExecutionListener 并提供我自己的实现。我正在使用 TaskletStep 注册它,但是,我从来没有看到 beforeStep/afterStep 方法应该输出的日志消息:

MyStepExecutionListener.java

public class MyStepExecutionListener implements StepExecutionListener {

 @Override
    public void beforeStep(StepExecution stepExecution) {
        // begin my own custom implementation
        LOGGER.info("Before the step!");
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
         // begin my own custom implementation
         LOGGER.info("After the step!");
        return stepExecution.getStatus();

    }
}

我在BatchConfig.java类中将我的 Tasklet 步骤定义为:

public BatchConfig {

@Bean
    public static org.springframework.batch.core.scope.JobScope jobScope() {
        org.springframework.batch.core.scope.JobScope jobScope = new org.springframework.batch.core.scope.JobScope();
        jobScope.setProxyTargetClass(true);
        jobScope.setAutoProxy(true);
        return jobScope;
    }

    @Bean
    public static org.springframework.batch.core.scope.StepScope stepScope() {
        org.springframework.batch.core.scope.StepScope stepScope = new org.springframework.batch.core.scope.StepScope();
        stepScope.setProxyTargetClass(true);
        stepScope.setAutoProxy(true);
        return stepScope;
    }

    @Bean
//    @StepScope
    public StepExecutionListener stepExecutionListener() {
        return new MyStepExecutionListener();
    }

 @Bean
    @Qualifier("s3FlatfFileReaderForMktgOffrs")
    @StepScope
    public S3FlatFileItemReader<FieldSet> s3FlatfFileReaderForMktgOffrs() {
        return new S3FlatFileItemReader<>(lineMapper());
    }

 @Bean
    @Qualifier("s3FlatfFileReaderCustom")
    @StepScope
    public S3FlatFileItemReader<FieldSet> s3FlatfFileReaderCustom() {
        // Custom class that Extends FlatFileItemReader
        return new S3FlatFileItemReader<>(lineMapper());
    }

  @Bean
    @Qualifier("myCustomFileItemReader")
    @StepScope
    public ItemStreamReader<List<FieldSet>> myCustomFileItemReader(
            @Value("#{jobParameters}") Map jobParameters) {

        String fileName = (String) jobParameters.get("fileName");
        String region = (String) jobParameters.get("region");
        String bucketName = awsS3EastBucket;
        if (StringUtils.equals(region, Regions.US_WEST_2.getName())) {
            bucketName = awsS3WestBucket;
        }

        // Custom class that Extends FlatFileItemReader
        S3FlatFileItemReader<FieldSet> s3FileItemReader = s3FlatfFileReaderCustom();

     
         s3FileItemReader.setResource(S3_PROTOCOL_PREFIX + bucketName + SLASH + fileName);
        }

        s3FileItemReader.setStrict(false);
        s3FileItemReader.setLinesToSkip(1);
        s3FileItemReader.setSaveState(false);

        AggregateItemReader aggregateItemReader = new AggregateItemReader(s3FileItemReader) {
            @Override
            protected String getItemKey(FieldSet item) {
                return item.readString(FIRST_NAME) + "-" +
                        item.readString(LAST_NAME);
            }
        };
        SynchronizedItemStreamReader<List<FieldSet>> fieldSetSynchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        fieldSetSynchronizedItemStreamReader.setDelegate(aggregateItemReader);
        return fieldSetSynchronizedItemStreamReader;
    }



@Bean(name = "myCustomStep")
    @Scope("prototype")
    @SuppressWarnings("unchecked")
    public Step myCustomStep(PlatformTransactionManager transactionManager) {
        TaskletStep step = stepBuilderFactory.get("myCustomStep")
                .<List<FieldSet>, List<MyPayLoadRecord>>chunk(250)
                .reader(myCustomFileItemReader(OVERRIDDEN_BY_EXPRESSION))
                .processor(myCustomProcessor())
                .writer(myCustomWriter())
                .faultTolerant()
                .skipPolicy(new AlwaysSkipItemSkipPolicy())
                .skip(DataValidationException.class)
                .listener(stepExecutionListener())
                .listener(new CustomReaderListener())
                .listener(new CustomProcessListener())
                .listener(new CustomWriteListener())
                .listener(new CustomSkipListener())
                .taskExecutor(batchTaskExecutor())
                .throttleLimit(maxThreads)
                .build();
        step.setTransactionManager(transactionManager);
        //step.registerStepExecutionListener(stepExecutionListener());
        step.registerChunkListener(new CustomChunkListener());
        return step;
    }
}

我已经注释掉step.registerStepExecutionListener(stepExecutionListener());并尝试设置侦听器,但都没有实现。我的印象是我应该只实现 StepExecutionListener 然后用 TaskletStep 注册它——我在这里遗漏了什么吗?

标签: javaspringspring-batch

解决方案


我不明白将您的步骤设置为原型范围 bean 的原因,但我无法使用类似于您共享的设置(使用 Spring Batch v4.3.3)重现该问题。这是一个简单的例子:

import java.util.Arrays;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
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.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
@EnableBatchProcessing
public class SO68217675 {

    @Bean
//    @StepScope // works with a step-scoped bean as well
    public StepExecutionListener stepExecutionListener() {
        return new MyStepExecutionListener();
    }

    @Bean
//    @Scope("prototype") // works with a prototype bean as well, but I don't understand the reason for that scope
    public Step step(StepBuilderFactory stepBuilderFactory) {
        return stepBuilderFactory.get("step")
                .<Integer, Integer>chunk(2)
                .reader(new ListItemReader<>(Arrays.asList(1, 2, 3, 4)))
                .writer(items -> items.forEach(System.out::println))
                .listener(stepExecutionListener())
                .build();
    }

    @Bean
    public Job job(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) {
        return jobBuilderFactory.get("job")
                .start(step(stepBuilderFactory))
                .build();
    }

    static class MyStepExecutionListener implements StepExecutionListener {

        @Override
        public void beforeStep(StepExecution stepExecution) {
            System.out.println("MyStepExecutionListener.beforeStep");
        }

        @Override
        public ExitStatus afterStep(StepExecution stepExecution) {
            System.out.println("MyStepExecutionListener.afterStep");
            return ExitStatus.COMPLETED;
        }
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext context = new AnnotationConfigApplicationContext(SO68217675.class);
        JobLauncher jobLauncher = context.getBean(JobLauncher.class);
        Job job = context.getBean(Job.class);
        jobLauncher.run(job, new JobParameters());
    }

}

此示例打印以下内容(如预期的那样):

MyStepExecutionListener.beforeStep
1
2
3
4
MyStepExecutionListener.afterStep

推荐阅读