我在使用 JavaMailSenderImpl 在 Spring Boot 应用程序中发送电子邮件时遇到了一些“问题”。
我正在尝试动态设置所有属性(我希望将来从数据库中读取它们)但是,由于我不知道的原因, Autowiring JavaMailSenderImpl 仅在我的 application.properties 中存在“spring.mail.host”时才有效.
我设置的值无关紧要(它可以为空,这无关紧要,因为我稍后设置了正确的值),但该属性必须存在,否则 Autowiring 将失败。
这是我的 Controller :
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]";
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
我可以把空的属性(property)留在那里,但感觉不对。
任何想法可能是什么原因?
最佳答案
Autowiring 接口(interface) JavaMailSender 而不是实现。
@Autowired
private JavaMailSender mailSender;
关于如果 spring.mail.host 不在 application.properties 中,则 JavaMailSenderImpl Autowiring 错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37415417/