I am creating a simple rest service. I have a rest controller class which has a post mapping endpoint "/insert" :
@RestController
@RequestMapping("/restapi")
public class RestService{
@PostMapping("/insert")
public void insert(@RequestBody String body){
DBClass db = new DBClass();
db.insert(body);
}
}
I got a class called DBClass which connects to the database and inserts objects. But if it fails, it will send an email about the error. Here is the insert method:
public void insertToFirestore(String body) {
try {
//insertDB
} catch (Exception e) {
MailService ms = new MailService();
ms.sendMail(to,subject,text);
}
}
And there is a MailService class where I do things about mails. It has a method called sendMail :
@Component
public class MailService {
@Autowired
JavaMailSender jms;
public void sendMail(String to,String subject,String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
jms.send(message);
}
}
I had done the configurations in the application.properties file. So if I try to send mail in the rest controller class it works just fine but when I try to send mail in MailService class Javamailsender object throws null pointer exception. I also tried sending mails other than Rest Controller class and they all threw the same exception.
@Autowired keyword initialize the java mail sender object only in Rest Controller class. What is the reason for that ?
Any help is appreciated.