最近同事在公共组件写的一个邮件发送功能,别人在使用的时候,一直有问题
问题:
启动服务程序一直报错JavaMailSender没有注入
排查:
-
查看是否写组件注入注解,没有问题
-
层级调用组件注入注解,也没有问题
但是还是一直报错JavaMailSender没有注入,奇怪了
调查下,业务是咋使用的:
![](https://img-blog.csdnimg.cn/img_convert/a75fd4f50cdb7d8c01dcb193954cee2e.png)
下来测试下公共组件:
启动公共组件,看看JavaMailSender的bean是否存在
测试是ok
那么问题就是服务a没有引用过去,为啥没有引过去呢?
那必须得看下pom文件了
![](https://img-blog.csdnimg.cn/img_convert/fb3f8720fdb9ab5c9c4401d495f5961a.png)
看见pom里面配置<optional>为true,真是太坑了
<optional>意思:
true表示两个项目之间依赖不传递;不设置optional或者optional是false,表示传递依赖
结论:
-
去掉<optional>true</optional>或者设置成false
-
服务a重新引用下spring-boot-starter-mail依赖
注意附官网文档地址:
Maven – Optional Dependencies and Dependency Exclusions
官网说明:
Project-A -> Project-B
The diagram above says that Project-A depends on Project-B. When A declares B as an optional dependency in its POM, this relationship remains unchanged. It's just like a normal build where Project-B will be added in Project-A's classpath.
Project-X -> Project-A
When another project (Project-X) declares Project-A as a dependency in its POM, the optional nature of the dependency takes effect. Project-B is not included in the classpath of Project-X. You need to declare it directly in the POM of Project X for B to be included in X's classpath.