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?
To disable the default filter, set the useDefaultFilters element of the @ComponentScan annotation to false.
You may use the exclude attribute with the annotation @SpringBootApplication.
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.
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 {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With