在xml配置了這個標簽后,spring可以自動去掃描base-package下面或者子包下面的java文件,如果掃描到有@Component @Controller@Service等這些注解的類,則把這些類注冊為bean
注意:如果配置了<context:component-scan>那么<context:annotation-config/>
標簽就可以不用再xml中配置了,因為前者包含了后者。
另外<context:annotation-config/>
還提供了兩個子標簽
<context:include-filter>
<context:exclude-filter>
再說明這兩個子標簽前,先說一下<context:component-scan>
有一個use-default-filters
屬性,改屬性默認為true,這就意味着會掃描指定包下的全部的標有@Component的類,並注冊成bean.也就是@Component的子注解@Service,@Reposity等。所以如果僅僅是在配置文件中這么寫
<context:component-scan base-package="tv.huan.weisp.web"/>
use-default-filter
此時為true那么會對base-package包或者子包下的所有的進行java類進行掃描,並把匹配的java類注冊成bean。
可以發現這種掃描的粒度有點太大,如果你只想掃描指定包下面的Controller,該怎么辦?此時子標簽context:incluce-filter就起到了用武之地。如下所示
<context:component-scan base-package="tv.huan.weisp.web .controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
這樣就會只掃描base-package指定下的有@Controller下的java類,並注冊成bean
但是因為use-dafault-filter
在上面並沒有指定,默認就為true,所以當把上面的配置改成如下所示的時候,就會產生與你期望相悖的結果(注意base-package包值得變化)
<context:component-scan base-package="tv.huan.weisp.web ">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
此時,spring不僅掃描了@Controller,還掃描了指定包所在的子包service包下注解@Service的java類
此時指定的include-filter
沒有起到作用,只要把use-default-filter
設置成false就可以了。這樣就可以避免在base-packeage配置多個包名這種不是很優雅的方法來解決這個問題了。
另外在我參與的項目中可以發現在base-package指定的包中有的子包是不含有注解了,所以不用掃描,此時可以指定<context:exclude-filter>
來進行過濾,說明此包不需要被掃描。綜合以上說明
use-dafault-filters=”false”
的情況下:<context:exclude-filter>
指定的不掃描,<context:include-filter>
指定的掃描