Disable automatic autowiring of third party Bean

612 Views Asked by At

I am implementing a third party library that uses Spring, which is declaring a Filter in the following way:

@Bean
@Autowired
public Filter filter() {
    return new Filter();
}

I load the configuration class to my application with a @Import(Configuration.class). My Spring Boot application loads the Filter and seems to try to use it, but I don't want that. How can I make Spring ignore such Beans, i.e., simply don't load them (supposing the third party library can work without them)?

2

There are 2 best solutions below

0
xerx593 On BEST ANSWER

We followed provider recommendation/decided for:

Appropriate and edit config

Means: Copy, paste and edit the original "Configuration" instead of/before importing/scanning it:

@Configuration
class MyConfig { 
  // copy, paste & edit original (com.third.party) Configuration (omit unwanted parts/beans)
} // <- use this

One alternative approach is:

Destroy Bean

As described by:

How can i remove a singleton spring bean from ApplicationContext?

..., we only need to "plug it" (e.g.) simple like:

@Bean
BeanFactoryAware myDestroy() {
  return (beanFactory) -> {
    ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition("filter"); // bean name (+ type, see [javadoc](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/support/BeanDefinitionRegistry.html))
  };
}

..also possible:

Replace Bean

Here we replace the Bean (by type and name), with an "NO-OP" bean:

@Primary @Bean
public Filter filter() { // same name & type!
    return new com.my.example.DoesNothingFilter(); // as name (and interface) implies
}

...

Ideally

Provider would make it @ConditionalOnXXX/bind it to @Profile! :)

... (+any other alternatives)

1
DwB On

Spring Boot includes the @Profile annotation.

Make the "to be ignored" classes with a specific @Profile and Spring Boot will ignore them when the identified profile is not active.

For example:

@Profile("BlammyProfile")
public class Blammy
{
  ...
}

Here is a Spring Profile Baeldung Article link