SpringBoot 多模塊項目(module)Service自動注入(@Autowired)

如果你因爲Service注入失敗,看過無數文章,甚至看過N份源碼仍不得要領,希望我能終結你的問題;


SpringBoot中Service自動注入很方便,例:

Service.class(接口類)

ServiceImpl.class(實現類)

Controller.class(使用類)

用以上三個類來說一下自動注入:

單項目:分別ServiceImpl頭上@Service,Controller中Service對象@Autowired即可享用;


Multi modules 場景,三個(種)類分別在三個module下:

moduleA : Service.class(com.example.moduleA )

moduleB : ServiceImpl.class ( com.example.moduleB )

moduleC : Controller.class ( com.example.moduleC )

此時B依賴A,C依賴A、B,添加好依賴關係。

如何自動注入?

1、接口、實現、使用類,姿勢不變,按單項目方式寫即可;

2、在moduleC的Application中做手腳!


如果你已經試過scanBasePackages,無論是在@SpringBootApplication方式還是@ComponentScan;

抑或試過@SpringBootApplication、@ComponentScan同時用,當你這麼做時,一定是絕望的。


解決辦法@SpringBootApplictaion(scanBasePackages="com.example")

核心就是:

Service 及 ServiceImpl均需在com.example包下


因爲Service、ServiceImpl同在com.example下(C可以不在),所以我看作是同一次scan過程;

比如若是這樣寫scanBasePackages={" com.example.moduleA , com.example.moduleB "},則會失敗;

當然(@ComponentScan="com.example")也是可以的,因爲前者@SpringBootApplication已經包含@ComponentScan;

真相大白,相信這樣很清楚了


獻給還在摸索的小夥伴。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章