springboot2 nacos JavaMailSenderImpl not found

背景:springboot2 nacos2.0.x 版本

项目添加了mail依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

nacos中也有mail相关配置:

spring.mail.username=xx
spring.mail.password=xx
spring.mail.host=smtp.qq.com

但是项目还是报错:

Description:

A component required a bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' in your configuration

那么问题出现在哪里呢?这要从源码说起……

从springboot的尿性,呃,不,优秀特性,我们知道,自动装配要从AutoXXX类开始,而mail的自动配置在MailSenderAutoConfiguration,所以我们打开它:

@Configuration
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)  // 【1.看这里!!!】
@EnableConfigurationProperties(MailProperties.class)  //【2.这里】
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })  // 【3.这里】
public class MailSenderAutoConfiguration {
	/**
	 * Condition to trigger the creation of a {@link MailSender}. This kicks in if either
	 * the host or jndi name property is set.
	 */
	static class MailSenderCondition extends AnyNestedCondition {
		MailSenderCondition() {
			super(ConfigurationPhase.PARSE_CONFIGURATION);
		}
		@ConditionalOnProperty(prefix = "spring.mail", name = "host")  // 【1.1】
		static class HostProperty {
		}
		@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
		static class JndiNameProperty {
		}
	}
}

上面的点2处 和 我们的配置spring.mail.xxx绑定,这也是我上面 nacos mail配置的由来;
上面的点3处就是给我们创建JavaMailSenderImpl对象了,它使用到了点2处的MailProperties配置;

重点是上面的点1处,引申到上面的 【1.1】处,一句话:
你需要在application.yml/properties文件中额外配置spring.mail.host=xxxx

目前不清楚是不是因为springboot先加载上面的mail自动配置类,然后再加载nacos的原因,虽然我们在nacos中配置了spring.mail.host=xxx,但是由于优先级没能加载到,导致文章开头的报错,望大佬看到后解惑,在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值