skip to content

Auto-Configuration

How Boot configures your application for you: the imports file, conditional annotations, ordering, overriding defaults, and debugging what did or did not apply. The single most useful Boot topic in interviews, because it demystifies everything else.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

25

What are @ConditionalOnClass and @ConditionalOnMissingClass, and why does Spring Boot auto-configuration rely on them?

level: juniorimportance: must knowfreq 70%

answer

  1. classpath presence, not bean presence
  2. ASM metadata read -> no NoClassDefFoundError
  3. backbone of Boot auto-config (Jackson/Web/DataSource)
  4. value = Class vs name = String
  5. multiple classes = AND

basics

~10 s

@ConditionalOnClass makes a bean/config load only if a named class is on the classpath; @ConditionalOnMissingClass only if it's absent. Boot uses them so auto-config activates just when the relevant library is present.

solid answer

~40 s

@ConditionalOnClass registers a bean or configuration only when the referenced class(es) exist on the classpath; @ConditionalOnMissingClass is the inverse. They are the backbone of Spring Boot auto-configuration: DataSourceAutoConfiguration only kicks in if a JDBC driver/HikariCP is present, WebMvcAutoConfiguration only if DispatcherServlet is present. Because the annotation is evaluated by reading class metadata (ASM), you can reference a type that may be absent without a NoClassDefFoundError — you pass the class via the value attribute or its name as a String. This 'react to what's on the classpath' model is why adding a starter dependency is often enough to get working defaults with zero configuration.

code

java · 16 lines
java
// Only configure a Jackson ObjectMapper bean when Jackson is on the classpath
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
public class MyJacksonConfig {

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

// String form when the referenced type may be absent from this loader
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "io.micrometer.core.instrument.MeterRegistry")
class OptionalMetricsConfig { /* ... */ }

go deeper

for a junior

Know it gates config on classpath presence and is why adding a starter 'just works'.

for a middle

Explain the ASM-metadata trick and value-vs-name attribute forms.

for a senior

Contrast with @ConditionalOnBean and describe short-circuiting whole auto-config classes.

for a principal

Discuss evaluation timing and how OnClassCondition avoids classloading during auto-config ordering.

## What they are `@ConditionalOnClass` and `@ConditionalOnMissingClass` are part of Spring Boot's `@Conditional` family (package `org.springframework.boot.autoconfigure.condition`). A `@Conditional` annotation attaches a `Condition` to a bean method or `@Configuration` class; Spring only registers that bean/config if the condition returns `true`. - **`@ConditionalOnClass`** — matches when the named class(es) are **present** on the classpath. - **`@ConditionalOnMissingClass`** — matches when the named class(es) are **absent**. ## Why auto-configuration needs them Spring Boot ships dozens of auto-configuration classes (listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`). They are all on the classpath, but most must stay **inert** unless the relevant library is actually present. Example: `JacksonAutoConfiguration` is guarded by `@ConditionalOnClass(ObjectMapper.class)` — no Jackson jar, no Jackson beans. This is the essence of 'convention over configuration': you add `spring-boot-starter-web`, the servlet/web classes appear, and the web auto-configs light up. ## The key trick: metadata, not class loading A naive check like `Class.forName(...)` would throw `NoClassDefFoundError` when the class is missing — defeating the purpose. Boot avoids this by evaluating conditions from **bytecode metadata via ASM** (`OnClassCondition` reads the annotation attributes without loading the referenced type). That is why you can safely write `@ConditionalOnClass(ObjectMapper.class)` on a config class even in an app where Jackson is absent. ### Two ways to name the class ```java @ConditionalOnClass(ObjectMapper.class) // typed – fine when THIS class can load it @ConditionalOnClass(name = "com.foo.Optional") // string – use when the type may be absent here ``` When the guarding class itself would fail to load the referenced type, use the `name`/`value` String form. In practice, on the **class/method being annotated**, the referenced type is read from the annotation metadata so the typed form is safe; you reach for the `name` attribute mostly for readability or truly optional deps. ## Placement and semantics - Can annotate a `@Configuration` class (gates everything inside) or a single `@Bean` method. - Multiple classes = **AND**: all must be present (`OnClass`) / all absent (`OnMissingClass`). - Evaluated at **context-refresh / bean-definition** time, before beans are instantiated. ## Edge cases & gotchas - **Classpath, not runtime state.** It answers 'is this type available?', not 'is a bean of it defined?' — that's `@ConditionalOnBean`. - **Order in auto-config.** `@ConditionalOnClass` at the top of an `@AutoConfiguration` class short-circuits the whole class cheaply, which is why Boot puts it there. - **User code.** You can use these in your own `@Configuration` to provide optional integrations (e.g., a bean only when a monitoring library is on the classpath). ## When to use Use `@ConditionalOnClass` when a feature only makes sense if a library is present; `@ConditionalOnMissingClass` to provide a fallback when a library is deliberately absent.

  • Why doesn't @ConditionalOnClass(SomeMissingType.class) throw NoClassDefFoundError when the type is absent?
    Boot's OnClassCondition reads the annotation attributes from the class file's metadata using ASM instead of loading the referenced type, so the missing class is never actually resolved by the classloader during evaluation.
  • What's the difference between @ConditionalOnClass and @ConditionalOnBean?
    @ConditionalOnClass checks whether a TYPE exists on the classpath; @ConditionalOnBean checks whether a bean DEFINITION of a type already exists in the context. Classpath availability vs. runtime bean presence are different questions.

saying these in an interview costs you the question

  • Claiming it checks whether a bean exists (that's @ConditionalOnBean)
  • Saying it uses Class.forName and can throw NoClassDefFoundError
  • Thinking multiple classes mean OR instead of AND

context

open as a page

What is a custom auto-configuration in Spring Boot, and how do you register it so Spring Boot picks it up automatically?

level: juniorimportance: must knowfreq 55%

basics

~10 s

A configuration class annotated with @AutoConfiguration that defines @Bean methods. You register it by listing its full class name in the file META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports so Spring Boot loads it on startup.

open as a page

What is @EnableAutoConfiguration and how does it end up on your application?

level: juniorimportance: must knowfreq 78%

basics

~10 s

@EnableAutoConfiguration tells Spring Boot to automatically configure beans based on what's on the classpath. You rarely write it directly because @SpringBootApplication already includes it.

open as a page

Explain @ConditionalOnProperty: its attributes (prefix, name, havingValue, matchIfMissing) and exactly when it matches.

level: middleimportance: must knowfreq 68%

basics

~20 s

@ConditionalOnProperty enables config based on a configuration property. It matches when the property (prefix + name) equals havingValue. matchIfMissing=true makes it match even when the property is absent, so a feature can be on by default.

open as a page

Why do @Bean methods in an auto-configuration almost always use @ConditionalOnMissingBean, and how do the conditional guards let a library back off?

level: middleimportance: must knowfreq 50%

basics

~20 s

@ConditionalOnMissingBean means 'only create this bean if the application hasn't already defined one.' It lets the library provide a sensible default while letting the app override it just by declaring its own bean of that type.

open as a page

How does Spring Boot discover auto-configuration classes, and what replaced spring.factories?

level: middleimportance: must knowfreq 62%

basics

~10 s

Boot reads a list of auto-configuration class names from a file on the classpath. Since Boot 2.7/3.0 that file is META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports; the old location was META-INF/spring.factories.

open as a page

How does @ConditionalOnMissingBean let a user override an auto-configured bean? What ordering rules make this work reliably?

level: seniorimportance: must knowfreq 66%

basics

~10 s

Auto-config beans are marked @ConditionalOnMissingBean, so they register only if the user hasn't defined one of that type. Because user @Configuration is processed before auto-configuration, a user bean wins and the default backs off.

open as a page

A bean you expected from auto-configuration isn't in the context. How do you use the condition report to find out why, and what are the usual causes?

level: seniorimportance: must knowfreq 50%

basics

~20 s

Run with --debug and find the auto-config under Negative matches; the reason line names the failing condition. Usual causes: a required class is missing from the classpath (@ConditionalOnClass), a property isn't set (@ConditionalOnProperty), or your own bean already exists so auto-config backed off (@ConditionalOnMissingBean).

open as a page

Why does auto-configuration ordering matter, and how does it interact with @ConditionalOnMissingBean?

level: seniorimportance: must knowfreq 45%

basics

~10 s

Ordering decides which auto-config class is evaluated first. @ConditionalOnMissingBean only sees beans already defined by earlier-processed classes, so the class that runs first defines the bean and later ones back off.

open as a page

How do you make Spring Boot print the auto-configuration condition evaluation report, and what is it for?

level: juniorimportance: should knowfreq 55%

basics

~20 s

Start the app with the --debug flag (or set debug=true in application.properties). Spring Boot then logs a report showing which auto-configurations were applied and which were skipped, helping you understand why a bean did or didn't get created.

open as a page

How do you control the order in which two Spring Boot auto-configuration classes are applied?

level: juniorimportance: should knowfreq 35%

basics

~10 s

Use @AutoConfigureBefore and @AutoConfigureAfter on the auto-configuration class, naming the other class. They force one to be processed before or after the other, instead of relying on the default order.

open as a page

Describe @ConditionalOnWebApplication, @ConditionalOnResource, and @ConditionalOnExpression — what each checks and a use case.

level: middleimportance: should knowfreq 45%

basics

~20 s

@ConditionalOnWebApplication matches when the app is a web app (servlet or reactive). @ConditionalOnResource matches when a classpath resource exists. @ConditionalOnExpression matches when a SpEL expression evaluates to true. Each gates beans/config on a different signal.

open as a page

Walk me through the sections of the condition evaluation report and what each tells you.

level: middleimportance: should knowfreq 45%

basics

~20 s

The report has four parts: Positive matches (auto-configs that were applied and why), Negative matches (ones skipped and the condition that failed), Exclusions (explicitly excluded configs), and Unconditional classes (configs with no conditions that always load).

open as a page

What are the ways to exclude a specific auto-configuration, and how do they differ?

level: middleimportance: should knowfreq 55%

basics

~10 s

Use exclude (by class) or excludeName (by string) on @SpringBootApplication/@EnableAutoConfiguration, or set the property spring.autoconfigure.exclude. All prevent a named auto-configuration class from being applied.

open as a page

What is the difference between @AutoConfigureBefore/@AutoConfigureAfter and @AutoConfigureOrder?

level: middleimportance: should knowfreq 40%

basics

~10 s

@AutoConfigureBefore/After express a relationship to a specific named auto-config class. @AutoConfigureOrder is a coarse numeric priority (lower runs earlier, default 0), like @Order, with no reference to any particular class.

open as a page

How do you control the order in which auto-configuration classes are applied, and why does ordering matter?

level: seniorimportance: should knowfreq 32%

basics

~10 s

Use the @AutoConfiguration annotation's before/after attributes, or the @AutoConfigureBefore, @AutoConfigureAfter, and @AutoConfigureOrder annotations. Ordering matters because conditions like @ConditionalOnBean depend on whether a prerequisite bean was already registered by an earlier auto-config.

open as a page

How do you package a custom Spring Boot starter, and why is it conventionally split into an 'autoconfigure' module and a 'starter' module?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A starter is usually two modules: an 'autoconfigure' module holding the @AutoConfiguration classes and code, and a near-empty 'starter' module that just declares dependencies (the autoconfigure module plus the libraries it needs). Apps depend on the starter.

open as a page

How can you access the ConditionEvaluationReport programmatically, e.g. in a test, instead of reading logs?

level: seniorimportance: should knowfreq 30%

basics

~10 s

The report is itself a bean. Call ConditionEvaluationReport.get(beanFactory) to obtain it, then inspect getConditionAndOutcomesBySource(). In tests, ApplicationContextRunner exposes it via assertThat(context).getBean(...) or by inspecting the runner's context so you can assert on matches.

open as a page

Walk through what AutoConfigurationImportSelector does at startup and how ordering and conditions are resolved.

level: seniorimportance: should knowfreq 40%

basics

~20 s

@EnableAutoConfiguration imports AutoConfigurationImportSelector. It loads candidate classes from the imports file, drops excluded ones, filters out candidates whose trigger classes are absent, orders the rest, and registers them — each then applies its own @Conditional guards.

open as a page

How did the @AutoConfiguration annotation change ordering and registration in Spring Boot 2.7+, and what are its before/after attributes?

level: seniorimportance: should knowfreq 30%

basics

~10 s

@AutoConfiguration (Boot 2.7+) is a meta-annotation bundling @Configuration(proxyBeanMethods=false). It has before, beforeName, after, afterName attributes so you set ordering inline instead of separate @AutoConfigureBefore/After annotations. Classes are now listed in AutoConfiguration.imports.

open as a page

How and when are @Conditional conditions evaluated, and how would you build a custom condition for the auto-config family?

level: principalimportance: should knowfreq 32%

basics

~10 s

Conditions run at context refresh during bean-definition processing, before beans are instantiated. To build one, implement Spring's Condition (or SpringBootCondition) interface and attach it with @Conditional; auto-config conditions extend SpringBootCondition and report a ConditionOutcome.

open as a page

Design a robust custom starter: how do you expose typed configuration and how do you test the auto-configuration in isolation?

level: principalimportance: should knowfreq 28%

basics

~10 s

Expose config with a @ConfigurationProperties class (bound via @EnableConfigurationProperties in the auto-config). Test with ApplicationContextRunner, which spins up a lightweight context, applies your auto-config and various properties/classpath conditions, and asserts which beans exist.

open as a page

Explain how the ConditionEvaluationReport is populated during context startup and why condition ordering affects what the report shows.

level: principalimportance: nice to knowfreq 15%

basics

~20 s

As Spring processes configuration classes, each @Conditional is evaluated by a ConditionEvaluator; the outcome is recorded into the ConditionEvaluationReport keyed by source. Because bean conditions (@ConditionalOnBean/OnMissingBean) only see beans registered so far, the order configs are processed changes the outcomes — and thus what the report records.

open as a page

How do you author a custom auto-configuration/starter correctly in Spring Boot 3, including ordering and back-off?

level: principalimportance: nice to knowfreq 28%

basics

~10 s

Annotate the class with @AutoConfiguration, guard beans with conditions like @ConditionalOnClass and @ConditionalOnMissingBean, register the class in META-INF/spring/...AutoConfiguration.imports, and control order with @AutoConfiguration(before/after) or @AutoConfigureBefore/After.

open as a page

Explain the deterministic ordering algorithm Spring Boot uses for auto-configurations, including the alphabetical fallback and cycle handling.

level: principalimportance: nice to knowfreq 18%

basics

~10 s

AutoConfigurationSorter first sorts classes alphabetically by name for a stable baseline, then re-sorts by @AutoConfigureOrder, then topologically applies @AutoConfigureBefore/@AutoConfigureAfter. Alphabetical is only a fallback; a cycle in before/after throws an error.

open as a page