是否有一些关于如何通过java配置配置MailSender的示例? 我见过的所有示例都使用xml来创建所需的bean:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.mycompany.com"/>
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="customerservice@mycompany.com"/>
<property name="subject" value="Your order"/>
</bean>
答案 0 :(得分:18)
您发布的代码(以及一些小的改进使其更易于配置)将转换为以下Java配置:
@Configuration
public class MailConfig {
@Value("${email.host}")
private String host;
@Value("${email.from}")
private String from;
@Value("${email.subject}")
private String subject;
@Bean
public JavaMailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
return javaMailSender;
}
@Bean
public SimpleMailMessage simpleMailMessage() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setSubject(subject);
return simpleMailMessage;
}
}
您还应该知道Spring Boot(您没有提及是否使用)可以为您自动配置JavaMailSender
。查看文档的this部分
答案 1 :(得分:0)
@Configuration
public class AppConfig {
@Value("${mail.host}")
private String host;
@Bean
public JavaMailSender emailService() {
JavaMailSender javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
return javaMailSender;
}
@Component
public class EmailServiceImpl implements EmailService {
@Autowired
public JavaMailSender emailSender;
public void sendSimpleMessage( String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
}
}