How do and work in Spring?

2019-01-22 13:06发布

问题:

I have several services:

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

annotated with @Service annotation. How can I exclude all services except one?


For example I want to use only MailService. I use the following configuration:

<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>

but now all services are excluded.

Why all services are excluded if exists one rule to include MailService?

回答1:

Include filters are applied after exclude filters, so you have to combine both expressions into one exclude filter. AspectJ expressions allow it (& is replaced by &amp; due to XML syntax):

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

This is a regex, so your expression ".*Service" means 'any number of any character followed by "Service"'. This explicitly excludes the MailService you want to include.



回答2:

Another way to perform this registration is with a single inclusion filter.

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

The "use-default-filters" attribute must be set to "false" in this case to keep Spring from adding a default filter equivalent to

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


回答3:

It looks like you want to use filter type "regex". Here's an example from the 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>