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

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

https://blog.csdn.net/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
来源:CSDN
原文:https://blog.csdn.net/qq_15329947/article/details/89149847
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/handsome1013/p/11059557.html