2017-03-29 129 views
0

余米尝试使用服务类来发送电子邮件,但我总是收到空。我看不到我的错误注射服务的失败

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

@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("[email protected]"); 
    mail.setFrom("[email protected]"); 
    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()); 
    } 

,我也创建豆类,所有政党成员显示控制器发送电子邮件,但我需要的服务(类)发送。 有什么想法?

+0

打印堆栈跟踪,你就会知道其中的例外被抛出。 –

+0

'@ Autowired'依赖不能为'null'。如果你自己创建一个服务实例,它只能是'null'。显示一些实际的代码。 –

回答

0

把JavaMailSender的一类,并与@Service注释像

@Service 
JavaMailSender { 
     void sendNotification(); 
} 

然后用它在另一个类像

@Autowired 
JavaMailSender notificationService; 

// use the service in a method 
void somewhere(){ 
     notificationService.sendNotification(yourArguments); 
} 
+0

这与我试图做的类似,创建服务并在其他类中调用它...有什么区别? –