Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ConditionalOnMissingBean can not be overridden

Tags:

spring-boot

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?

like image 395
tomi Avatar asked Jul 26 '19 10:07

tomi


Video Answer


1 Answers

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.

like image 143
Bond - Java Bond Avatar answered Nov 29 '22 13:11

Bond - Java Bond