基於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