liveBook · Manning

@conditionalonmissingbean

As explained in Spring in Action, Sixth Edition

@ConditionalOnMissingBean is a Spring Boot condition annotation that matches when no bean of a specified type or name is already present.

@ConditionalOnMissingBean lets Spring Boot autoconfiguration provide a bean only when an explicitly configured bean of the required type or name is absent. section 15.2.2

MongoTemplate autoconfiguration

When no MongoTemplate bean exists, the MongoTemplate autoconfiguration passes its condition and creates one. If a MongoTemplate has already been configured, this condition prevents that automatic replacement. section 15.2.2

{
  "contexts": {
    "application-1": {
      "positiveMatches": {
...
        "MongoDataAutoConfiguration#mongoTemplate": [
          {
            "condition": "OnBeanCondition",
            "message": "@ConditionalOnMissingBean (types:
                org.springframework.data.mongodb.core.MongoTemplate;
                SearchStrategy: all) did not find any beans"
          }
        ],
...
      },
      "negativeMatches": {
...
        "DispatcherServletAutoConfiguration": {
          "notMatched": [
            {
              "condition": "OnClassCondition",
              "message": "@ConditionalOnClass did not find required
                  class 'org.springframework.web.servlet.
                                                 DispatcherServlet'"
            }
          ],
          "matched": []
        },
...
      },
      "unconditionalClasses": [
...
        "org.springframework.boot.autoconfigure.context.
                          ConfigurationPropertiesAutoConfiguration",
...
      ]
    }
  }
}

Inspect /actuator/conditions to see positive matches, negative matches, and unconditional classes, including the condition message confirming that no MongoTemplate bean was found. section 15.2.2

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains the missing-bean check through MongoTemplate and shows how /conditions reports the resulting match.
Examples
Uses MongoTemplate autoconfiguration and an Actuator /conditions response showing a positive match.
What it assumes
Assumes familiarity with Spring beans and autoconfiguration while illustrating the missing-bean behavior through MongoTemplate.
What you can do after
Diagnose autoconfiguration decisions with the Actuator /conditions endpoint.
How it connects
Connects Spring Boot autoconfiguration with beans, Spring Boot Actuator, and @ConditionalOnClass.

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.