基於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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!