【源码分析-Spring Boot】-7.Spring Boot Email 是如何装配的


Spring Boot Email 邮件发送:【从零开始学Spring Boot】-7.Spring Boot Email邮件发送

1.Email 自动装配

JavaMailSender 仅有一个实现 JavaMailSenderImpl

在 Mail 的自动装配类 MailSenderAutoConfiguration 中有如下定义

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class)
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
public class MailSenderAutoConfiguration {

    static class MailSenderCondition extends AnyNestedCondition {

        MailSenderCondition() {
            super(ConfigurationPhase.PARSE_CONFIGURATION);
        }

        @ConditionalOnProperty(prefix = "spring.mail", name = "host")
        static class HostProperty {

        }

        @ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
        static class JndiNameProperty {

        }
    }
}

MailSenderAutoConfiguration 通过 @Import 对 MailSenderJndiConfiguration 和 MailSenderPropertiesConfiguration 进行导入,这两个类中声明了 JavaMailSenderImpl 对象

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Session.class)
@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
@ConditionalOnJndi
class MailSenderJndiConfiguration {

    private final MailProperties properties;

    MailSenderJndiConfiguration(MailProperties properties) {
        this.properties = properties;
    }

    @Bean
    JavaMailSenderImpl mailSender(Session session) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setDefaultEncoding(this.properties.getDefaultEncoding().name());
        sender.setSession(session);
        return sender;
    }

    @Bean
    @ConditionalOnMissingBean
    Session session() {
        String jndiName = this.properties.getJndiName();
        try {
            return JndiLocatorDelegate.createDefaultResourceRefLocator().lookup(jndiName, Session.class);
        }
        catch (NamingException ex) {
            throw new IllegalStateException(String.format("Unable to find Session in JNDI location %s", jndiName), ex);
        }
    }
}

文章作者: Soulballad
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Soulballad !
评论
 上一篇
【从零开始学Spring Boot】-8.Spring Boot Actuator监控 【从零开始学Spring Boot】-8.Spring Boot Actuator监控
1.简介1.1 概述 Spring Boot includes a number of additional features to help you monitor and manage your application when you
下一篇 
【从零开始学Spring Boot】-7.Spring Boot Email邮件发送 【从零开始学Spring Boot】-7.Spring Boot Email邮件发送
1.简介1.1 概述 The Spring Framework provides an easy abstraction for sending email by using the JavaMailSender interface, an
  目录