为了账号安全,请及时绑定邮箱和手机立即绑定

使用 spring 邮件发送电子邮件时出现空指针异常

使用 spring 邮件发送电子邮件时出现空指针异常

慕森卡 2021-11-03 14:22:48
我正在尝试使用 spring 来做电子邮件功能(为了我的学习目的)。以下是代码片段:@AutowiredstaticApplicationContext applicationContext;/** * <p> * Utility classes, which are collections of static members, are not meant to be * instantiated. Even abstract utility classes, which can be extended, should * not have public constructors. *  * Java adds an implicit public constructor to every class which does not define * at least one explicitly. Hence, at least one non-public constructor should be * defined. *  * </p> */private EmailUtility() {}//@Autowired//private static JavaMailSender mailSender;public static void sendSimpleMessage(String to, String subject, String text, boolean trainTicket,        boolean flightTicket) throws MessagingException {    JavaMailSender mailSender = applicationContext.getBean("mailSender",JavaMailSenderImpl.class);    MimeMessage message = mailSender.createMimeMessage();    String pathToAttachment = "";    MimeMessageHelper helper = new MimeMessageHelper(message, true);    helper.setTo(to);    helper.setSubject(subject);    helper.setText(text);    if (trainTicket && !flightTicket) {        pathToAttachment = AppConstants.TRAIN_TICKET_FILE;    } else if (!trainTicket && flightTicket) {        pathToAttachment = AppConstants.FLIGHT_TICKET_FILE;    }    if (Objects.nonNull(pathToAttachment) && !pathToAttachment.isEmpty()) {        FileSystemResource file = new FileSystemResource(new File(pathToAttachment));        helper.addAttachment("Ticket", file);    }    mailSender.send(message);}}我的应用程序上下文:<!-- Step 3: Add support for component scanning --><context:component-scan base-package="com.patcyy.vamonos" /><!-- Step 4: Add support for conversion, formatting and validation support --><mvc:annotation-driven/>我在初始化 JavaMailSender 时遇到空指针异常。(在这一行 JavaMailSender mailSender = applicationContext.getBean("mailSender",JavaMailSenderImpl.class);)
查看完整描述

1 回答

?
精慕HU

TA贡献1845条经验 获得超8个赞

我认为主要问题是您将某种服务定义为实用程序。无论如何,如果您想在非托管对象中使用 Spring 托管 bean,您可以执行以下操作


@Component public class ContextInitializer {


@Autowired

private JavaMailSender mailSender;


@PostConstruct

public void postConstruct() {

    EmailUtility.setMailSender(mailSender);

}

}


并在 EmailUtility 类中添加一个 setter 方法。


查看完整回答
反对 回复 2021-11-03
  • 1 回答
  • 0 关注
  • 343 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信