關於Spring註解自動掃描中的 base-package
阿新 • • 發佈:2019-02-05
之前用springmvc的時候,會將mvc的容器和spring根容器分開配置,同時指定根容器掃描的目標和mvc容器掃描的目標,往往是這樣子:
<!-- 跟容器排除@Controller註解 --> <context:component-scan base-package="org.xxx" use-default-filter="true"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
<!-- mvc容器只包含@Controller註解 -->
<context:component-scan base-package="org.xxx" use-default-filter="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
OK,完全可以,而且大多數都是這麼省事兒的一寫就行了。
但是今天我很搓火,因為啟動一個專案太慢了,一直在等spring上下文初始化完成,而且根和mvc上下文初始化時間差不多。
於是我就開啟spring的debug級別的log,我了個擦,無論是根還是mvc容器都把整個專案的class掃描了一邊,一邊掃描一邊利用上面的“包含/排除”過濾器驗證。
---------------------------
之後我一琢磨,覺得直接在 base-package 上定義好 根上下文和mvc上下文的 起點目錄應該會更好一些,這樣的話每個上下文只需先驗證目錄(包)名是否符合然後再掃描下面的class豈不是會省去大量的掃描時間。
於是我先搜尋了一下base-package 通配模式,果然支援ant樣式,*和**
重新配置了以下自動掃描:
<!-- 根上下文只掃描 dao, service.impl 以及 webservice 包下的class --> <context:component-scan base-package="org.xxx.**.dao, org.xxx.**.service.impl, org.xx.**.webservice" />
<!-- mvc上下文只掃描 controller 包下的class -->
<context:component-scan base-package="org.xxx.**.controller" />
直接使用預設的過濾器就行了,貌似根本不用在去定義包含或排除的過濾器,而且初始化速度槓槓的 , 用debug-log查看了以下spring的輸出,完全沒問題,也沒有出現兩容器重複bean的情況。
--------------------------------------