Video in progress

Strong Middle 🌱 Spring

Why does @ConditionalOnMissingBean show up so often in auto-configurations, and how do you tell which auto-configuration kicked in?

Boot creates a bean on the condition "if you haven't provided your own", which is why you can replace any default with your own bean. Which conditions matched shows up in the Conditions Evaluation Report printed with --debug, or in /actuator/conditions.

📖 Answer

A typical Boot auto-configuration:

@AutoConfiguration
@ConditionalOnClass(ObjectMapper.class)
class JacksonAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        return builder.createXmlMapper(false).build();
    }
}

If you declare your own ObjectMapper, Boot doesn't create its own. Auto-configurations are processed after your configuration, so the condition works correctly.

But if you replace the whole bean, the spring.jackson.* settings stop working too. Often a customizer is enough:

@Bean
Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
    return b -> b.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}

To see what matched:

java -jar app.jar --debug

It prints "Positive matches" (the ones that applied) and "Negative matches" (the ones that didn't, with the reason). For example: DataSourceAutoConfiguration did not match: @ConditionalOnClass did not find required class...