基于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对象:spa
@Autowired
private BService bService;
1
2
而且调用bService的方法:.net
bService.doSomething();
1
测试代码提示会报错:对象
bService could not be autowired, no candidate bean...
1
这是由于模块A的@SpringBootApplication注解默认扫描范围为A的启动类所在的包(com.example.modulea)及其子包,因此此时模块A并无扫描到模块B的stereotype,那么天然没法在模块A中注入模块B的Service类。blog
解决办法
若是模块A和模块B的包名相同,则
在模块A的SpringBootApplication扩大其扫描包的范围:it
@SpringBootApplication(scanBasePackages = {"com.example"})
1
或io
@SpringBootApplication(scanBasePackages = {"com.example.modulea", "com.example.moduleb"})
---------------------
做者:Jake Weng
来源:CSDN
原文:https://blog.csdn.net/qq_15329947/article/details/89149847
版权声明:本文为博主原创文章,转载请附上博文连接!class