spring boot: disable @Bean definition from external @Configuration class

Viewed 737

I'm using a libreary that contains a @Configuration class which's setting this bean:

@Configuration
public abstract class BaseConfig {
 
    @Bean
    public ISchedulerService schedulerService() {
        return new HapiSchedulerServiceImpl().setDefaultGroup(HAPI_DEFAULT_SCHEDULER_GROUP);
    }

    // other beans
}

I need to replace the @Bean definition by my own.

Is there anyway to disable this concreate @Bean definition?

I know, I'm able to disable a @Configuration class using for example:

@SpringBootApplication(exclude = {BaseConfig.class})

However, it's goinf to disable all other @Bean definitions.

Any idea?

2 Answers

Maybe you can use @Primary for your new configuration, but that can lead to another issues. If you can modify the BaseConfig then you can probably use something like

@Bean
@ConditionalOnMissingBean
public ISchedulerService schedulerService() {
    return new HapiSchedulerServiceImpl().setDefaultGroup(HAPI_DEFAULT_SCHEDULER_GROUP);
}

and then you should be safe to define your own config.

Did you try enable bean overriding? In your application.properties:

spring.main.allow-bean-definition-overriding=true

But it is difficult to guess which bean will have priority because the bean creation order is determined by dependency relationships mostly influenced in runtime.

If you can modify BaseConfig, you probably should use one of the @Condition... annotation like the @bilak said.

Related