我正在尝试使用 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);)
精慕HU
相关分类