Home > Net >  Spring bean overriding does not throw exception when default settings is not allowing
Spring bean overriding does not throw exception when default settings is not allowing

Time:01-25

I have the below configuration class.

@Configuration
public class BeanConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
}

I am creating object mapper (Jackson) bean to use as a model mapper but I believe Spring must throw BeanDefinitionOverrideException as I am overriding ObjectMapper. I know this exception is added and thrown in such cases after Spring Boot 2.1 and am using 2.4.x versions.

spring.main.allow-bean-definition-overriding=false // default config

I am wondering why I am not getting such exception?

CodePudding user response:

Because of the @ConditionalOnMissingBean in the default ObjectMapper bean configuration provided by spring-boot , it will only define and configure a default ObjectMapper bean if you do not define one by yourself.

Now as you define an ObjectMapper , it causes spring-boot stop defining the default one. So in the end you just have one ObjectMapper bean and hence BeanDefinitionOverrideException will not happen.

If you create another @Configuration and define one more ObjectMapper with the same name , you should produce BeanDefinitionOverrideException :

@Configuration
@Import(BeanConfig2.class)
public class BeanConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
}

@Configuration
public class BeanConfig2 {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
}
  •  Tags:  
  • Related