Jordi
Jordi

Reputation: 23187

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

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?

Upvotes: 2

Views: 3130

Answers (3)

Anderson
Anderson

Reputation: 2742

A workaround here.

  1. Exclude the config as you mentioned.
@SpringBootApplication(exclude = {BaseConfig.class})
  1. Add a new class SubConfig, which extends BaseConfig and override any bean method you want.

  2. Add @Import(SubConfig.class) to enable it.

BTW, same workaround for the bean imported by auto-configuration.

  1. Exclude the auto-config by adding a property
spring.autoconfigure.exclude=\
  com.foo.bar.BaseConfig
  1. Add a new class SubConfig, which extends BaseConfig and override any bean method you want.

  2. Add @ImportAutoConfiguration(SubConfig.class) to enable it.

Upvotes: 0

M. Dudek
M. Dudek

Reputation: 1085

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.

Upvotes: 0

bilak
bilak

Reputation: 4922

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.

Upvotes: 1

Related Questions