Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exclude @Component from @ComponentScan

I have a component that I want to exclude from a @ComponentScan in a particular @Configuration:

@Component("foo") class Foo { ... } 

Otherwise, it seems to clash with some other class in my project. I don't fully understand the collision, but if I comment out the @Component annotation, things work like I want them to. But other projects that rely on this library expect this class to be managed by Spring, so I want to skip it only in my project.

I tried using @ComponentScan.Filter:

@Configuration  @EnableSpringConfigured @ComponentScan(basePackages = {"com.example"}, excludeFilters={   @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)}) public class MySpringConfiguration {} 

but it doesn't appear to work. If I try using FilterType.ASSIGNABLE_TYPE, I get a strange error about being unable to load some seemingly random class:

Caused by: java.io.FileNotFoundException: class path resource [junit/framework/TestCase.class] cannot be opened because it does not exist

I also tried using type=FilterType.CUSTOM as following:

class ExcludeFooFilter implements TypeFilter {     @Override     public boolean match(MetadataReader metadataReader,             MetadataReaderFactory metadataReaderFactory) throws IOException {         return metadataReader.getClass() == Foo.class;     } }  @Configuration @EnableSpringConfigured @ComponentScan(basePackages = {"com.example"}, excludeFilters={   @ComponentScan.Filter(type=FilterType.CUSTOM, value=ExcludeFooFilter.class)}) public class MySpringConfiguration {} 

But that doesn't seem to exclude the component from the scan like I want.

How do I exclude it?

like image 767
ykaganovich Avatar asked Sep 24 '13 22:09

ykaganovich


People also ask

How do I disable component scan?

To disable the default filter, set the useDefaultFilters element of the @ComponentScan annotation to false.

How do I exclude specific packages in Spring boot?

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

How do you exclude certain beans?

You need a method with '@Bean' annotation that crate and instance of the class, or annotate the class with '@Componen', '@Service' etc. annotation for annotation scanning to find it ? Does @ComponentScan(excludeFilters = @ComponentScan. Filter(type = FilterType.


1 Answers

The configuration seem alright, except that you should use excludeFilters instead of excludes:

@Configuration @EnableSpringConfigured @ComponentScan(basePackages = {"com.example"}, excludeFilters={   @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)}) public class MySpringConfiguration {} 
like image 54
Sergi Almar Avatar answered Sep 25 '22 20:09

Sergi Almar