ComponentScan.Filter not filtering @Configuration class in spring boot

Viewed 154

ComponentScan.Filter not filtering @Configuration class. I'm using spring boot 2.2.12 with spring-context 5.2.12.

SpringBoot class

@EnableMBeanExport
@ComponentScan(basePackages = "com.init”,
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.init.server.ServerAConfig.class)})
@SpringBootApplication()
public class MyApplication extends SpringBootServletInitializer {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(MyApplication.class);
    }

}

Under the basepackage com.init, there is a configurtion class ServerAConfig.


@Configuration
@ComponentScan(basePackages = {"com.execute.server”})
public class ServerAConfig {
}

Under package com.execute.server I have class MyServerA.java

My expectation was, MyServerA will not be available in the ApplicationContext

            for (String beanName : applicationContext.getBeanDefinitionNames()) {
                System.out.println(beanName);
            }

but when i run the above print after the boot up it shows MyServerA there in the ApplicationContext. My expectation was MyServerA will not be initialized. Also tried with different FilterType.

2 Answers

I think you need to get rid of the @SpringBootApplication() annotation, it has a component scan built in that will scan everything in the directory the class is in:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    // ...
}

So you either add the annotations above that you want to keep and drop the @SpringBootApplication().

Or you can use the scanBasePackages or scanBasePackageClasses of the @SpringBootApplication() annotation and drop your own @Componentscan instead. I think the former method would be better, because this would be tedious.

You could also move the class you want to exclude so it is easier to define what you want to scan without scanning it using the second method.

Use AutoConfigurationExcludeFilter to filter auto configurations classes

@EnableMBeanExport
@ComponentScan(basePackages = "com.init”,
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)})
@SpringBootApplication()
public class MyApplication extends SpringBootServletInitializer {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(MyApplication.class);
    }

}
Related