我试图从ExecutionContext
检索弹簧批次SkipListener
。
这是我尝试过的(我依靠注释而不是接口来实现我的侦听器):
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());
}
}
}
然而,当logSkippedEmail
被提升时,MailSendException
方法永远不会被执行。当我删除saveStepExecution
方法时,logSkippedEmail
再次执行MailSendException
。
我注册我的MailSkipListener
如下:
@Bean
public Step messagesDigestMailingStep(EntityManagerFactory entityManagerFactory) {
return stepBuilderFactory
.get("messagesDigestMailingStep")
.<UserAccount, UserAccount>chunk(5)
...
.writer(itemWriter)
.listener(mailSkipListener)//Here
.build();
}
我想在这里实现的是从我的ExecutionContext
中检索SkipListener
。怎么能实现这一目标?似乎没有办法自动装载theExecutionContext
。
您可以在StepExecutionListener
上实现MailSkipListener
以在stepExecution
方法中保存beforeStep()
中的上下文:
public class MailSkipListener implements StepExecutionListener {
@Override
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
这是一个相当古老的问题,但我也在努力解决这个问题。我最后两次注册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();
}