注入服务失败

时间:2017-03-29 17:24:53

标签: java spring-boot

我正在尝试使用服务类发送电子邮件,但我总是收到空。我无法看到我的错误

这是我的代码 这是我的通知服务

@Autowired
private JavaMailSender javaMailSender;
/*
@Autowired
public  NotificationService(JavaMailSender javaMailSender){
    this.javaMailSender = javaMailSender;

}
*/
@Async
public void sendNotificaitoin(String msg) throws MailException, InterruptedException {

    System.out.println("Sleeping now...");
    Thread.sleep(10000);

    System.out.println("Sending email...");

    SimpleMailMessage mail = new SimpleMailMessage();
    mail.setTo("ghanem.dhafer@gmail.com");
    mail.setFrom("ulquiorra.cifer19924@gmail.com");
    mail.setSubject("NOTIFICATION");
    mail.setText(msg);
    javaMailSender.send(mail);

    System.out.println("Email Sent!");

这是我调用服务的地方:

@Autowired
private NotificationService notificationService;
try {

    notificationService.sendNotificaitoin(msg);
    }catch( Exception e ){
        // catch error
        System.out.println("Error Sending Email: " + e.getMessage());
    } 

我也创建bean,所有tuto显示在控制器中发送电子邮件但我需要发送服务(类)。 任何想法?

1 个答案:

答案 0 :(得分:0)

将JavaMailSender放在一个类中,并使用@Service和

进行注释
@Service
JavaMailSender {
        void sendNotification();
}

然后在另一个类中使用它,比如

@Autowired
JavaMailSender notificationService;

// use the service in a method
void somewhere(){
        notificationService.sendNotification(yourArguments);
}
相关问题