Sub topic 4
Reacting to the classpath
Auto-configuration often has to answer one question first: is the library I integrate with on the classpath? This chapter covers @ConditionalOnClass and @ConditionalOnMissingClass, how Spring Boot evaluates them without triggering class-loading errors, and the mistakes that cause NoClassDefFoundError in a library that is supposed to be optional.
This chapter assumes you know how @Configuration and @Bean classes work, and that you have seen the AutoConfiguration.imports file and the general idea of @Conditional from the earlier chapters. Bean conditions and ordering have their own chapters, so they only appear here where they support the examples.
Why the classpath is a condition
A Spring Boot starter brings in libraries, and an application's dependencies decide which libraries are present. Spring Boot's own spring-boot-autoconfigure module ships configuration for dozens of technologies, but most of them are not on your classpath. Without a way to skip a configuration whose library is missing, the module would break every application that lacks one of those libraries.
Class conditions fix that. A configuration class says "apply me only if this class can be loaded", and Spring Boot skips it otherwise.
| Annotation | Matches when | Typical use |
|---|---|---|
| `@ConditionalOnClass` | All named classes are present | Enable integration with a library |
| `@ConditionalOnMissingClass` | The named class is absent | Provide a fallback when a library is absent |
@ConditionalOnClass
The annotation has two attributes. They can be combined, and all listed classes must be present.
valuetakes class literals, such as@ConditionalOnClass(GreetingService.class).nametakes fully qualified class names as strings, such as@ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper").
The GreetingAutoConfiguration from the topic plan already uses it:
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@ConditionalOnProperty(prefix = "greeting", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
}If GreetingService is not on the classpath, the whole class is skipped.
Why a class literal is safe here
A class literal looks dangerous. If the class is missing, wouldn't the JVM throw NoClassDefFoundError when it reads the annotation?
Spring avoids this by not loading your configuration class through reflection while it evaluates the condition. It reads the class file bytes with ASM, a bytecode reader, and inspects annotation metadata from there. In that metadata a class literal is only a name, so a missing class does not fail the read.
The safety holds only while Spring is reading metadata. Once a class is loaded normally, any reference to a missing type in its fields, method signatures, or bodies can fail. That leads to the common errors below.
Class literal or name?
Use the class literal when the class is always on your own module's classpath, as with GreetingService in the greeting module. Use name for classes from optional third-party libraries.
A class literal on a type-level annotation is safe, but it ties you to a compile-time reference. If you accidentally mark the dependency as required, you lose the benefit of the condition. A string name needs no compile-time dependency at all, which makes it the safer default for optional libraries.
The value attribute has a restriction. Spring Boot's documentation warns that value on a @Bean method can fail, which the next section explains.
@ConditionalOnMissingClass
This is the inverse. It matches when a class is absent. It accepts only value as strings of class names, because the whole point is that the class may not exist and cannot be written as a literal.
@ConditionalOnMissingClass("com.fasterxml.jackson.databind.ObjectMapper")Use it for fallbacks. It is rarer than @ConditionalOnClass, and it is often better to express the fallback as "user did not define a bean", which you will see in the bean conditions chapter. Use @ConditionalOnMissingClass when the alternative depends on a library being absent.
Putting optional-library code in nested classes
The most common error with class conditions is applying @ConditionalOnClass to a @Bean method. The condition might say "skip", but Spring reads the configuration class's method signatures through reflection before it evaluates the method condition. If a signature mentions a missing type, such as the return type, the JVM throws NoClassDefFoundError.
The fix is to put code that references an optional type inside a nested @Configuration class and put the class condition on that nested class. Spring reads the nested class's metadata first, applies the condition, and loads the nested class only if the condition passes.
Here is a complete example. It formats greetings as JSON when Jackson is present and as plain text otherwise.
package com.example.format;
public interface GreetingFormatter {
String format(String name);
}package com.example.format;
public class PlainGreetingFormatter implements GreetingFormatter {
@Override
public String format(String name) {
return "Hello, " + name;
}
}package com.example.format;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class JsonGreetingFormatter implements GreetingFormatter {
private final ObjectMapper mapper;
public JsonGreetingFormatter(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public String format(String name) {
try {
return this.mapper.writeValueAsString(Map.of("greeting", "Hello, " + name));
}
catch (JsonProcessingException ex) {
throw new IllegalStateException(ex);
}
}
}package com.example.format;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@AutoConfiguration
public class FormatterAutoConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper")
static class JsonFormatterConfiguration {
@Bean
@ConditionalOnMissingBean(GreetingFormatter.class)
GreetingFormatter jsonGreetingFormatter() {
return new JsonGreetingFormatter(new ObjectMapper());
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingClass("com.fasterxml.jackson.databind.ObjectMapper")
static class PlainFormatterConfiguration {
@Bean
@ConditionalOnMissingBean(GreetingFormatter.class)
GreetingFormatter plainGreetingFormatter() {
return new PlainGreetingFormatter();
}
}
}Two details make this work:
- The outer class mentions no Jackson type. It stays loadable on any classpath.
- The
@Beanmethod returns theGreetingFormatterinterface, notJsonGreetingFormatter. Even inside the nested class, the signature then names only types that are always present.
For the module itself to compile, Jackson must be a compile-time dependency. It must not be a required runtime dependency of the library. In Maven, mark it <optional>true</optional>. In Gradle, use compileOnly. If you declare it as a normal dependency, every consumer gets Jackson transitively and the condition always matches.
How the check stays cheap
Auto-configuration evaluates class conditions early and often. Spring Boot goes further than reading each class individually. Auto-configuration classes can have a generated metadata file, META-INF/spring-autoconfigure-metadata.properties, produced by the spring-boot-autoconfigure-processor annotation processor at build time. It records each class's @ConditionalOnClass requirements. Spring Boot's OnClassCondition filter uses this to discard auto-configurations whose required classes are missing before it reads or loads the configuration classes at all.
You do not need this processor for a first custom auto-configuration. Add it to a shared library with many auto-configurations if startup time matters. Class conditions work correctly without it.
Common errors
@ConditionalOnClasson a@Beanmethod with an optional return type. This fails withNoClassDefFoundErrorwhen the library is absent. Move the bean into a nested@Configurationclass, as shown above.- A class literal in an annotation Spring does not read through ASM. Class literals are safe in annotations on configuration classes that Spring reads as metadata. They are not safe in ordinary application code, where the JVM resolves the type. If you are unsure, use
name. - A dependency that is not really optional. If Jackson arrives transitively,
@ConditionalOnClassalways matches, and your fallback never runs. Check the dependency scope. - A typo in a string class name.
name = "com.fasterxml.jackson.databind.Objectmapper"does not fail. The condition just never matches. The conditions report shows this, as the next section explains. - Using
@ConditionalOnClassto mean "bean exists". A class on the classpath says nothing about whether the user defined a bean. Use@ConditionalOnBeanor@ConditionalOnMissingBeanfor that.
Diagnosing class conditions
Start the application with --debug and read the conditions evaluation report. A class condition appears in the negative matches like this:
FormatterAutoConfiguration.PlainFormatterConfiguration:
Did not match:
- @ConditionalOnMissingClass found unwanted class 'com.fasterxml.jackson.databind.ObjectMapper' (OnClassCondition)If a configuration you expected is missing, search the report for the class name. The message names the class that was or was not found. For @ConditionalOnClass it reads did not find required class.
Testing both branches
ApplicationContextRunner can hide classes from the context's class loader with FilteredClassLoader. That lets one test run exercise a classpath where Jackson is absent, even though Jackson is on the test classpath.
package com.example.format;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class FormatterAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FormatterAutoConfiguration.class));
@Test
void usesJsonWhenJacksonIsPresent() {
this.contextRunner.run(context -> assertThat(context)
.getBean(GreetingFormatter.class)
.isInstanceOf(JsonGreetingFormatter.class));
}
@Test
void fallsBackWhenJacksonIsMissing() {
this.contextRunner
.withClassLoader(new FilteredClassLoader("com.fasterxml.jackson.databind"))
.run(context -> assertThat(context)
.getBean(GreetingFormatter.class)
.isInstanceOf(PlainGreetingFormatter.class));
}
}The second test is the one that protects you from the nested-class mistake. If you moved Jackson code into the outer class, it would fail with NoClassDefFoundError instead of passing.
Exercise
A library's auto-configuration has a @Bean method JsonGreetingFormatter jsonFormatter() annotated with @ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper"), directly inside the @AutoConfiguration class. On an application without Jackson, startup fails with NoClassDefFoundError. Why does the condition not protect the application, and how do you fix it?
Show answer
Spring reads the configuration class's method signatures through reflection before it evaluates the method-level condition. The return type JsonGreetingFormatter references ObjectMapper, so loading it fails when Jackson is absent. Fix it by moving the method into a nested static @Configuration class annotated with @ConditionalOnClass(name = ...), and by making the method return the GreetingFormatter interface so the signature names no optional type.
Exercise
You mark Jackson as a normal (non-optional) dependency in your auto-configuration library and add a PlainFormatterConfiguration guarded by @ConditionalOnMissingClass for Jackson. An application that never declared Jackson still gets the JSON formatter. What happened, and how do you confirm it?
Show answer
Jackson reached the application's classpath transitively through your library, so the class is present and @ConditionalOnMissingClass never matches. Change the dependency to optional in Maven or compileOnly in Gradle. To confirm, run the application with --debug and look in the negative matches for PlainFormatterConfiguration, which reports that it found the unwanted class com.fasterxml.jackson.databind.ObjectMapper.