Psycho Punch
Psycho Punch

Reputation: 6902

How do I exclude all @Component classes except for one under @ComponentScan?

I have the following annotation in my code:

@ComponentScan(basePackageClasses={MyClass.class},
            excludeFilters={@Filter(Component.class)}, //@Component
            includeFilters={@Filter(type=ASSIGNABLE_TYPE, classes=MyClass.class)}
        )

MyClass is annotated with @Component but still want to include it during component scan. However, component scan filters seem to use and logic instead of or. How do I achieve what I want to do?

Upvotes: 5

Views: 3113

Answers (1)

tan9
tan9

Reputation: 3620

@Configuration is more deterministic than @ComponentScan at all cases.

Rather than workarounding the @ComponentScan annotation. You should try to explicitly list your MyClass.class in a @Configuration class as a @Bean, like:

@Configuration
public class MyClassConfiguraiton {

    @Bean
    public MyClass myClass() {
        return new MyClass();
    }
}

Then @Import the configuration class explicitly instead of the @ComponentScan annotation:

@Import(MyClassConfiguratrion.class)

Or import it via component scan mechanism (since @Configuration is meta-annotated with @Component).

Upvotes: 2

Related Questions