如何在<context:include-filter>和<context:exclude-filter>中使用Spring?

Fra*_*mos 25 configuration spring

我有几个服务:

  • 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>
Run Code Online (Sandbox Code Playgroud)

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

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

Dav*_*vid 33

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

<context:component-scan base-package="example" use-default-filters="false">
    <context:include-filter type="aspectj" expression="example..MailService*" />
</context:component-scan>
Run Code Online (Sandbox Code Playgroud)

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

<context:include-filter type="annotation" 
                        expression="org.springframework.stereotype.Component"/>
Run Code Online (Sandbox Code Playgroud)

  • +1 - 设置`use-default-filters ="false"`是防止扫描同一个基础包中其他组件的关键.也适用于正则表达式. (11认同)

axt*_*avt 13

排除过滤器后会应用包含过滤器,因此您必须将两个表达式合并到一个排除过滤器中.AspectJ表达式允许它(由于XML语法而&被替换&amp;):

<context:exclude-filter type="aspectj" 
    expression="example..*Service* &amp;&amp; !example..MailService*" />
Run Code Online (Sandbox Code Playgroud)

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

  • @lisak:更明确的说法:包含过滤器不能包含排除过滤器排除的类型. (3认同)

ear*_*las 10

看起来你想要使用过滤器类型"正则表达式".以下是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>
Run Code Online (Sandbox Code Playgroud)