本文介绍了从SkipListener检索ExecutionContext时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从SkipListener检索春批ExecutionContext

以下是我的尝试(我依靠注释而不是接口来实现我的监听器):

import com.xxxx.domain.UserAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.core.annotation.OnSkipInWrite;
import org.springframework.mail.MailSendException;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MailSkipListener {

    private StepExecution stepExecution;

    @BeforeStep
    public void saveStepExecution(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }

    @OnSkipInWrite
    public void logSkippedEmail(UserAccount userAccount, Throwable t) {
        if (t instanceof MailSendException) {
            MailSendException e = (MailSendException) t;
            log.warn("FailedMessages: " + e.getFailedMessages());
        }
    }
}
但是,当引发MailSendException时,不会执行logSkippedEmail方法。当我删除saveStepExecution方法时,如果是MailSendException,则会再次执行logSkippedEmail

我注册我的MailSkipListener如下:

@Bean
public Step messagesDigestMailingStep(EntityManagerFactory entityManagerFactory) {
    return stepBuilderFactory
            .get("messagesDigestMailingStep")
            .<UserAccount, UserAccount>chunk(5)

            ...

            .writer(itemWriter)
            .listener(mailSkipListener)//Here
            .build();
}
我在这里尝试实现的是从我的SkipListener检索ExecutionContext。怎样才能做到这一点呢?似乎无法自动套接ExecutionContext

推荐答案

这是一个相当老的问题,但我也在这个问题上苦苦挣扎。为了使其正常工作,我最终注册了两次skiplistener,一次是作为StepExecutionListener,另一次是作为SkipListener。很糟糕,但似乎很管用:

@Bean
public Step messagesDigestMailingStep(EntityManagerFactory entityManagerFactory) {
    return stepBuilderFactory
        .get("messagesDigestMailingStep")
        .<UserAccount, UserAccount>chunk(5)

        ...

        .writer(itemWriter)
        .listener((StepExecutionListener) mailSkipListener) // <--- 1
        .listener((SkipListener) mailSkipListener)          // <--- 2
        .build();
}

这篇关于从SkipListener检索ExecutionContext时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-06 05:01