【问题标题】:Using spring batch config how to send a mail and how to configure in the job使用spring batch config如何发送邮件以及如何在job中配置
【发布时间】:2016-01-27 15:19:09
【问题描述】:

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

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

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

【问题讨论】:

标签: spring spring-batch spring-jms


【解决方案1】:

您可以使用 spring 电子邮件支持和工作侦听器。

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

【讨论】:

  • 你在哪里给作业配置中的“JobCompletionNotificationListener”类名
  • 在你的joblistener类名是JobCompletionNotificationListener你在你的工作配置中的哪里配置
  • 只需将其配置为 spring bean 并自动装配它。我现在更改了配置代码。希望你清楚。
  • 请将 mail.jar 添加到您的类路径中。
  • 如果你能google一下就更容易了。有很多可用的例子
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2018-07-05
  • 2019-03-04
  • 2019-03-01
相关资源
最近更新 更多