我们在Spring MVC中的配置中一般会遇到这两个标签,作为<context:component-scan />的子标签出现。我们在使用这两个标签时候要注意以下几点:
1、我们经常Spring-applicationContext.xml和Spring-MVC.xml分开配置,在Spring-MVC.xml中只对@Controller扫描即可,作为一个控制器,其他事情不需要做,在Spring-applicationContext.xml只对一些事务逻辑的注解扫描。context:exclude-filter 指定扫描包时要排除的类,context:include-filter 指定扫描时要包含的类。
2、现在给定一个项目包的机构:
com.wzy.controlller
com.wzy.service
如,给两个包机构
(1)Spring-MVC.xml中的配置:
<!-- 扫描@Controller注解 -->
<context:component-scan base-package="com.wzy.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
不难看出,最终将包写上,而不能这样写base-package=”com.wzy”,这种写法对于include-filter来讲它都会扫描,而不是仅仅扫描@Controller,这点需要注意,他一般会导致一个常见的错误,那就是事务不起作用,补救的方法是添加use-default-filters=”false”。如:
<context:component-scan base-package="com.wzy" use-default-filters="false">
<!--
指定只扫描哪些组件,默认是全都扫描进来,所以需要设置use-default-filters="false"
-->
<context:include-filter
type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
(2)Spring-applicationContext.xml中的配置:
type="annotation":
<!-- 配置扫描注解,不扫描@Controller注解 -->
<context:component-scan base-package="com.wzy">
<!--
type="annotation":按照注解进行排除,标注了指定注解的组件不要扫描
expression:注解的全类名
-->
<context:exclude-filter
type="annotation"
expression=" org.springframework.stereotype.Controller"/>
</context:component-scan>
type="assignable"
<context:component-scan base-package="com.wzy">
<!--
type="assignable" :指定排除某个具体的类,按照类排除
expression:类的全类名
-->
<context:exclude-filter
type="assignable"
expression="com.hh.service.BookService"/>
</context:component-scan>
可以看出,这是要扫描com.wzy包下的所有子类,不包含@Controller了,对于exculude-filter不存在包不精确后都进行扫描的问题。