在xml文件配置了<context:component-scan>標(biāo)簽后,spring容器可以自動去掃描base-pack所指定的包或其子包下面的java類文件贷笛,如果掃描到有@Component、@Controller、@Service 、@Repository等注解修飾的Java類映砖,則將這些類注冊為spring容器中的bean。
注意點:
如果配置了<context:component-scan>標(biāo)簽元素罩旋,那么<context:annotation-config/>標(biāo)簽就可以不用在xml中配置了啊央,因為前者包含了后者。
-
<context:component-scan>有一個use-default-filters屬性涨醋,該屬性值默認為true,這就意味著會掃描指定包下的
全部的有@Component瓜饥、@Controller、@Service 浴骂、@Repository等注解修飾的Java類乓土,則將這些類注冊為
spring容器中的bean。
例如在配置文件中添加如下代碼:<context:component-scan base-package="com.bank.account.web"/>
因為此時屬性Use-default-filter的值為true溯警,那么會對base-package包或者子包下所有的java類進行掃描,并
把匹配的java類注冊成spring容器中的bean趣苏。 -
<context:component-scan>還提供了兩個子標(biāo)簽:
-
<context:include-filter>
-
如果你只想掃描指定包下面的Controller,可以借助于子標(biāo)簽<context:incluce-filter>梯轻,如下代碼所示:
<context:component-scan base-package="com.bank.account.web.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
以上xml的配置就會告之spring容器只掃描base-package(此處:com.bank.account.web.controller)指定包下的有@Controller修飾的java類食磕,并注冊成spring窗口中的bean。
-
但是因為use-dafault-filter在上面并沒有指定喳挑,默認就為true彬伦,所以當(dāng)把上面的配置改成如下所示的時候,就會與之相反的結(jié)果(注意base-package包值得變化)
<context:component-scan base-package="com.bank.account.web"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
此時伊诵,spring不僅掃描了@Controller修飾的javaod 单绑,還掃描了指定包或其子包下有@Service 、
@Repository注解修飾的java類此時指定的include-filter沒有起到作用曹宴,只要把use-default-filter設(shè)置成
false就可以了搂橙。這樣就可以避免在base-packeage配置多個包名。
-
<context:exclude-filter>
項目中,在base-package指定的包中有的子包是不含有注解的笛坦,所以這些包可以不進行掃描区转,此時可以指定
<context:exclude-filter>來進行過濾,說明此包不需要被掃描版扩。
Use-dafault-filters=”false”的情況下:<context:exclude-filter>指定的包不進行相應(yīng)注解的掃描蜗帜,
<context:include-filter>指定包或其子包進行相應(yīng)注解的掃描。
-