基于SpringBoot的多模块项目引入其他模块时@Autowired无法注入其他模块stereotype注解类对象的问题解决...

本文聚焦基于SpringBoot的多模块项目,当一个模块引入其他模块时,使用@Autowired无法注入其他模块stereotype注解类对象。原因是默认扫描范围局限,给出解决办法,若两模块包名相同,可在模块A的SpringBootApplication扩大扫描包范围。

基于SpringBoot的多模块项目引入其他模块时@Autowired无法注入其他模块stereotype注解类对象的问题解决

https://blog.youkuaiyun.com/qq_15329947/article/details/89149847

多模块注入问题
在多模块(如,基于SpringBoot的微服务)项目中,往往需要在一个模块中注入另一个模块中的服务层(@Service标记)或持久层(@Repository标记)类的对象。
假设模块A依赖于模块B,并且需要注入模块B中的BService对象,那么第一步,需要在A的pom文件中引入B作为依赖:

<dependency>
<groupId>com.example</groupId>
<artifactId>module-b</artifactId>
<version>1.0</version>
</dependency>
1
2
3
4
5
第二步,在A中的特定类中注入B的BService对象:

@Autowired
private BService bService;
1
2
并且调用bService的方法:

bService.doSomething();
1
测试代码提示会报错:

bService could not be autowired, no candidate bean...
1
这是因为模块A的@SpringBootApplication注解默认扫描范围为A的启动类所在的包(com.example.modulea)及其子包,所以此时模块A并没有扫描到模块B的stereotype,那么自然无法在模块A中注入模块B的Service类。

解决办法
如果模块A和模块B的包名相同,则
在模块A的SpringBootApplication扩大其扫描包的范围:

@SpringBootApplication(scanBasePackages = {"com.example"})
1

@SpringBootApplication(scanBasePackages = {"com.example.modulea", "com.example.moduleb"})
---------------------
作者:Jake Weng
来源:优快云
原文:https://blog.youkuaiyun.com/qq_15329947/article/details/89149847
版权声明:本文为博主原创文章,转载请附上博文链接!

转载于:https://www.cnblogs.com/handsome1013/p/11059557.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值