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

我正在尝试使用 spring 来做电子邮件功能(为了我的学习目的)。以下是代码片段:


@Autowired

static

ApplicationContext 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);)


慕森卡
浏览 349回答 1
1回答

精慕HU

我认为主要问题是您将某种服务定义为实用程序。无论如何,如果您想在非托管对象中使用 Spring 托管 bean,您可以执行以下操作@Component public class ContextInitializer {@Autowiredprivate JavaMailSender mailSender;@PostConstructpublic void postConstruct() {&nbsp; &nbsp; EmailUtility.setMailSender(mailSender);}}并在 EmailUtility 类中添加一个 setter 方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java