Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do <context:include-filter> and <context:exclude-filter> work in Spring?

Tags:

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?

like image 705
Francisco Villa Ramos Avatar asked Sep 14 '10 15:09

Francisco Villa Ramos


People also ask

What does include filter in spring do?

The ANNOTATION filter type includes or excludes classes in the component scans which are marked with given annotations.

What is context component scan in spring?

Auto Components Scanning Put this “ context:component ” in bean configuration file, it means, enable auto scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan this folder and find out the bean (annotated with @Component) and register it in Spring container.

How do I ignore a spring boot package?

You may use the exclude attribute with the annotation @SpringBootApplication.


2 Answers

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"/> 
like image 136
David Avatar answered Sep 25 '22 18:09

David


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.

like image 21
axtavt Avatar answered Sep 23 '22 18:09

axtavt