'How to exclude Spring beans from @Configuration/scan packages?

I have a @Configuration ExternalConfig class from other library, I cannot modify it. I need to import it but also remove some beans from this external config.

Here is the ExternalConfig I CANNOT MODIFY (basically I want to remove Bean1.class and Bean2.class scanned from com.config.external)

@Configuration
@ComponentScan({"com.config.external"})
public class ExternalConfig {

}

And here is my custom config :

@Import(ExternalConfig.class)
@ComponentScan(basePackages = {"com.config.external"}, excludeFilters = {
        @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value= {Bean1.class, Bean2.class})
})
@Configuration
public class CustomConfig {

}

But it does not work, Bean1 and Bean2 got injected into application context. Is there something I can do about it ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source