我知道我可以使用以下属性来自动创建JavaMailSender
bean:
spring.mail.host=hostname
spring.mail.port=587
spring.mail.username=username
spring.mail.password=password
但是,如何定义这些属性来创建两个JavaMailSender
bean,以便可以从不同的SMTP服务器发送电子邮件?
我尝试定义以下属性:
# Properties for sender 1
spring.mail.host=hostname
spring.mail.port=587
spring.mail.username=username
spring.mail.password=password
# Properties for sender 2
spring.mail.host1=hostname2
spring.mail.port1=587
spring.mail.username1=username2
spring.mail.password1=password2
但是,这不能按我预期的那样工作,所以如何使用Spring boot创建两个JavaMailSender
bean?
答案 0 :(得分:3)
Spring Boot只会在发现JavaMailSender
属性后才初始化一个spring.mail.*
。如果需要多个,则必须自己定义这些bean。如果只需要属性主机,端口,用户名和密码,则可以使用以下简单配置:
@Configuration
public class MailConfiguration {
@Bean
@ConfigurationProperties(prefix = "spring.mail.primary")
public JavaMailSender primarySender() {
return new JavaMailSenderImpl();
}
@Bean
@ConfigurationProperties(prefix = "spring.mail.secondary")
public JavaMailSender secondarySender() {
return new JavaMailSenderImpl();
}
}
但是,如果您还想配置spring.mail.properties.*
,则不起作用。为此,您的配置会有些复杂,因为您必须执行以下操作:
MailProperties
创建两个@ConfigurationProperties
的bean。MailSenderPropertiesConfiguration
中的Spring boot相似的方式使用MailProperties
。此后,您可以像平常一样使用spring.mail.primary.*
属性和spring.mail.secondary.*
属性。例如:
spring.mail.primary.host=host1
spring.mail.primary.port=port1
spring.mail.primary.username=username1
spring.mail.primary.password=password1
spring.mail.secondary.host=host2
spring.mail.secondary.port=port2
spring.mail.secondary.username=username2
spring.mail.secondary.password=password2
之后,您可以自动连接primarySender
和secondarySender
。确保使用@Qualifier
注释告诉Spring哪个:
@Service
public class MailService {
private JavaMailSender primarySender;
private JavaMailSender secondarySender;
public MailService(
@Qualifier("primarySender") JavaMailSender primarySender,
@Qualifier("secondarySender") JavaMailSender secondarySender) {
this.primarySender = primarySender;
this.secondarySender = secondarySender;
}
}