我在使用 JavaMailSenderImpl 在 Spring Boot 应用程序中发送电子邮件时遇到了一些“问题”。
我正在尝试动态设置所有属性(我希望将来从数据库中读取它们),但是,由于我不知道的原因,自动装配 JavaMailSenderImpl 仅在我的 application.properties 中存在“spring.mail.host”时才有效。
我设置的值并不重要(它可以是空的,这并不重要,因为我稍后设置了正确的值),但是该属性必须存在,否则自动装配将失败。
这是我的控制器:
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MailController {
@Autowired
private JavaMailSenderImpl ms;
@RequestMapping("/mail")
public String send(Model model){
SimpleMailMessage message;
String fromEmail="[email protected] /cdn-cgi/l/email-protection";
String toEmail ="xxxxxxx";
Properties mailProperties = new Properties();
mailProperties.put("mail.smtp.starttls.enable", true);
mailProperties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
ms.setHost("smtp.gmail.com");
ms.setPort(587);
ms.setUsername("xxxx");
ms.setPassword("yyyyy");
ms.setJavaMailProperties(mailProperties);
message = new SimpleMailMessage();
message.setSubject("Test email");
message.setFrom(fromEmail);
message.setTo(toEmail);
message.setText("Something something");
try{
ms.send(message);
}
catch(MailException ex){
System.err.println(ex.getMessage());
}
return "OK";
}
}
使用此 application.properties 可以正常工作(发送电子邮件):
#springboot-starter-mail properties
spring.mail.host=
但如果我删除该行,则会抛出此异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.mail.javamail.JavaMailSenderImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
... 19 common frames omitted
我可以把空置的房产留在那里,但感觉不对。
有什么想法可能是什么原因吗?
自动装配 JavaMailSender 接口而不是实现。
@Autowired
private JavaMailSender mailSender;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)