【问题标题】:How do <context:include-filter> and <context:exclude-filter> work in Spring?<context:include-filter> 和 <context:exclude-filter> 如何在 Spring 中工作?
【发布时间】:2011-04-12 05:54:32
【问题描述】:

我有几项服务:

  • example.MailService
  • example.LDAPService
  • example.SQLService
  • example.WebService
  • example.ExcelService

使用@Service 注释进行注释。如何排除除一项之外的所有服务?


例如,我只想使用 MailService。我使用以下配置:

<context:component-scan base-package="example">
    <context:include-filter type="aspectj" expression="example..MailService*" />
    <context:exclude-filter type="aspectj" expression="example..*Service*" />
</context:component-scan>

但现在所有服务都被排除在外了。

如果存在一个包含 MailService 的规则,为什么会排除所有服务?

【问题讨论】:

    标签: spring configuration


    【解决方案1】:

    您似乎想使用过滤器类型“正则表达式”。这是来自Spring Reference 的示例:

    <beans>
    
       <context:component-scan base-package="org.example">
          <context:include-filter type="regex" expression=".*Stub.*Repository"/>
          <context:exclude-filter type="annotation"
                                  expression="org.springframework.stereotype.Repository"/>
       </context:component-scan>
    
    </beans>
    

    【讨论】:

    • 如果您只想在组件扫描中包含一个类型,则正则表达式过滤器类型是最简单的方法。
    【解决方案2】:

    包含过滤器在排除过滤器之后应用,因此您必须将两个表达式组合成一个排除过滤器。 AspectJ 表达式允许它(由于 XML 语法,&amp;amp;&amp;amp; 替换):

    <context:exclude-filter type="aspectj" 
        expression="example..*Service* &amp;&amp; !example..MailService*" />
    

    这是一个正则表达式,因此您的表达式“.*Service”表示“任意数量的任意字符后跟“Service””。这明确排除了您要包含的 MailService。

    【讨论】:

    • 您是什么意思“在排除过滤器之后应用包含过滤器”?排除过滤器首先被解释并包含过滤器然后允许这些类型,尽管它们是在排除过滤器中定义的?这完全不适合我
    • @lisak:更清楚地说:包含过滤器不能包含被排除过滤器排除的类型。
    • 请您看一下这个stackoverflow.com/q/4584509/306488好吗?这让我发疯了......
    【解决方案3】:

    执行此注册的另一种方法是使用单个包含过滤器。

    <context:component-scan base-package="example" use-default-filters="false">
        <context:include-filter type="aspectj" expression="example..MailService*" />
    </context:component-scan>
    

    在这种情况下,“use-default-filters”属性必须设置为“false”,以防止 Spring 添加等效于的默认过滤器

    <context:include-filter type="annotation" 
                            expression="org.springframework.stereotype.Component"/>
    

    【讨论】:

    • +1 - 设置use-default-filters="false" 是防止扫描同一基本包中的其他组件的关键。也适用于正则表达式。
    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多