Spring配置之<context:include-filter/>和<context:exclude-filter/>详解

我们在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不存在包不精确后都进行扫描的问题。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值