1. 程式人生 > >SpringBoot 多模組專案(module)Service自動注入(@Autowired)

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;

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

獻給還在摸索的小夥伴。