多模块注入问题
在多模块(如,基于SpringBoot的微服务)项目中,往往需要在一个模块中注入另一个模块中的服务层(@Service标记)或持久层(@Repository标记)类的对象。
假设模块A依赖于模块B,并且需要注入模块B中的BService对象,那么第一步,需要在A的pom文件中引入B作为依赖:
<dependency>
<groupId>com.example</groupId>
<artifactId>module-b</artifactId>
<version>1.0</version>
</dependency>
第二步,在A中的特定类中注入B的BService对象:
@Autowired
private BService bService;
并且调用bService的方法:
bService.doSomething();
测试代码提示会报错:
bService could not be autowired, no candidate bean...
这是因为模块A的@SpringBootApplication注解默认扫描范围为A的启动类所在的包(com.example.modulea)及其子包,所以此时模块A并没有扫描到模块B的stereotype,那么自然无法在模块A中注入模块B的Service类。
解决办法
如果模块A和模块B的包名相同,则
在模块A的SpringBootApplication扩大其扫描包的范围:
@SpringBootApplication(scanBasePackages = {"com.example"})
或
@SpringBootApplication(scanBasePackages = {"com.example.modulea", "com.example.moduleb"})