tomi
tomi

Reputation: 423

@ConditionalOnMissingBean can not be overridden

I'm using Spring Boot 2.1.6.RELEASE and I'm wondering how @ConditionalOnMissingBean should be used?

Example configuration:

@Configuration
public class MyAutoConfiguration {

  @Bean
  @ConditionalOnMissingBean
  public Foo foo() {
    return new Foo();
  }
}
@Configuration
@Import(MyAutoConfiguration.class)
public class AppConfiguration {

  @Bean
  public Foo foo() {
    return new Foo("some property");
  }
}

AppConfiguration.class and MyAutoConfiguration.class are in different modules.

Error:

The bean 'foo', defined in class path resource [com/example/autoconf/configuration/AppConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [com/my/configuration/MyAutoConfiguration.class] and overriding is disabled.

How to use @ConditionalOnMissingBean without setting spring.main.allow-bean-definition-overriding=true property?

Upvotes: 7

Views: 2393

Answers (2)

ursa
ursa

Reputation: 4611

Method I've used to solve "overriding" problem both with auto-configuration and with explicit configuration:

Shared module:

@Configuration
public class SharedAutoConfiguration {

  @Bean
  @ConditionalOnMissingBean
  public Foo foo() {
    return new Foo();
  }
}

+

META-INF/spring.factories
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
        x.y.z.SharedAutoConfiguration 

App with explicit configuration:


@Configuration
public class AppSpecificConfiguration 
    extends SharedAutoConfiguration { // <== extends base configuration

  @Bean
  @Override // <== overrides
  public Foo foo() {
    return new AppSpecificFoo();
  }
}

@Import(AppSpecificConfiguration.class)
public class App {

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

Upvotes: 0

Ammar
Ammar

Reputation: 4024

For MyAutoConfiguration to be picked up by Spring Boot as auto-configuration it need to be declared in META-INF/spring.factories as below

org.springframework.boot.autoconfigure.EnableAutoConfiguration=x.y.z.MyAutoConfiguration 

For more details related to custom auto-configurations have a look here.

Upvotes: 1

Related Questions