使用spring batch配置如何发送邮件以及如何在作业中配置

时间:2016-01-25 10:31:11

标签: spring spring-batch spring-jms

我需要使用spring batch config发送邮件。在邮件状态(成功或失败)的邮件中,现在能够从csv读取数据并写入数据库。我需要发送邮件的数据库。 请任何人建议我 这是我的java配置文件作业配置

return jobs.get("insertIntoDbFromCsvJob")
            .start(readRegistrations())
                .build();
    }

这里是readRegistrations()步骤是从csv读取数据并写入数据库。 现在我需要发送邮件,如果该步骤成功或失败。

1 个答案:

答案 0 :(得分:2)

您可以使用春季电子邮件支持和工作听众。

    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost("localhost");
        javaMailSenderImpl.setUsername("");
        javaMailSenderImpl.setPassword("");
        javaMailSenderImpl.setProtocol("smtp");
        javaMailSenderImpl.setPort(25);
        return javaMailSenderImpl;
    }

    @Bean
    public SimpleMailMessage templateMessage() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo("to@gmail.com");
        mailMessage.setSubject("Job Status");
        mailMessage.setFrom("test@test.com");
        return mailMessage;
    }

实施监听器

@Component
public class JobCompletionNotificationListener extends
        JobExecutionListenerSupport {

    private static final Logger log = LoggerFactory
            .getLogger(JobCompletionNotificationListener.class);

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private SimpleMailMessage templateMessage;

    @Override
    public void afterJob(JobExecution jobExecution) {
        if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
            log.info("!!! JOB FINISHED! Time to verify the results");
            SimpleMailMessage mailMessage = new SimpleMailMessage(
                    templateMessage);
            mailMessage.setText("Job Success");
            javaMailSender.send(mailMessage);
        }
    }
}

作业配置

@Autowired
private JobCompletionNotificationListener listener;

@Bean
public Job importUserJob(JobBuilderFactory jobs, Step s1,
        JobExecutionListener listener) {
    return jobs.get("importUserJob").incrementer(new RunIdIncrementer())
            .listener(listener).flow(s1).end().build();
}