初学SpringBoot难免会遇到一些问题
昨天在编写JavaMail工具类的时候,静态方法调用静态变量,这是很正常的操作,当时也没多想,直接静态注入。
@Component
public class JavaMailUtil {
@Autowiredprivate static JavaMailSenderImpl mailSender;/*** 发送包含简单文本的邮件*/public static void sendText(String title,String text) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();// 设置收件人simpleMailMessage.setTo(new String[] {
"3213452105@qq.com"});//寄件人simpleMailMessage.setFrom("857776215@qq.com");simpleMailMessage.setSubject(title);simpleMailMessage.setText(text);// 发送邮件mailSender.send(simpleMailMessage);System.out.println("JavaMailUtil类提示:---邮件已发送---");}
}
结果就出现了空指针异常。查询了之后发现 @Autowired不能给静态变量注入,所以出现空指针异常。然后开始找解决方法,暂时找到了一个能用的方法。
@Component
public class JavaMailUtil {
private static JavaMailSenderImpl mailSender;@Autowiredprivate JavaMailSenderImpl javaMailSender;@PostConstructpublic void init(){
mailSender = javaMailSender;}/*** 发送包含简单文本的邮件*/public static void sendText(String title,String text) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();// 设置收件人simpleMailMessage.setTo(new String[] {
"3213452105@qq.com"});//寄件人simpleMailMessage.setFrom("857776215@qq.com");simpleMailMessage.setSubject(title);simpleMailMessage.setText(text);// 发送邮件mailSender.send(simpleMailMessage);System.out.println("JavaMailUtil类提示:---邮件已发送---");}
}
这样就注入成功了。