『Bug记录』JavaMailSender 注入失败,空指针异常的解决

最近有个需求,用户评论邮件通知我,然后使用 JavaMailSender

由于在 properties 中配置了 mail ,这里直接注入 JavaMailSender

问题溯源

package com.sugar.wxblog.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
import java.util.Map;
/**
 * 功能描述: 邮件工具箱
 *
 * @author 方糖
 * @date 2021/11/30 20:24
 */
@Component
@EnableAsync
public class MailUtils {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;

    @Async
    public void sendSimpleMail(String toAccount, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            System.out.println(mailProperties);
            message.setFrom(mailProperties.getUsername());
            message.setTo(toAccount);
            message.setSubject(subject);
            message.setText(content);
            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

当去测试时发现,报空指针异常,MailProperties 并没有注入成功。

@Test
void contextLoads() {
	new MailUtils().sendSimpleMail("sugartech@gmail.com","","");
}

在这里插入图片描述

问题排查

当使用 @Autowired 注入后,交由 Spring 管理,不能使用 new 对象使用,必须从 Spring 容器中获得对象。

	@Autowired
    MailUtils mailUtils;

    @Test
    void contextLoads() {
        mailUtils.sendSimpleMail("xiaoheikeji@vip.qq.com","Java 邮件发送测试","null");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值