Sub topic 12
Excluding auto-configurations
This chapter assumes you can run a Spring Boot application, you know application.properties, and you have read the earlier chapters on AutoConfiguration.imports, conditions, and the --debug conditions report. Here you learn how to remove an auto-configuration from processing, when that is the right tool, and what goes wrong when it is not.
Why exclude at all
Most of the time you don't need to exclude anything. Auto-configurations already back off when you define your own bean (@ConditionalOnMissingBean) or when a property turns them off (@ConditionalOnProperty). Exclusion is the blunt option. It removes a whole auto-configuration class from the candidate list before any of its conditions run.
Exclusion fits in these cases:
- A library on the classpath triggers an auto-configuration you don't want, and the auto-configuration has no property to disable it.
- The auto-configuration fails at startup in your setup. A common case is
DataSourceAutoConfigurationwhen JDBC classes are on the classpath but the application has no database yet. - You want to be certain a class is never evaluated, for example to avoid a slow or side-effect-prone initialization.
Three ways to exclude
You can exclude by class, by class name, or by property. All three feed the same exclusion set.
By class: the `exclude` attribute
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Application {
}@SpringBootApplication.exclude is an alias for @EnableAutoConfiguration.exclude. If you put @EnableAutoConfiguration on a class directly, it takes the same attribute. The class reference is checked by the compiler, so a typo or a removed class breaks the build. That is a benefit when the class is always on your classpath. It is a problem when the class might be missing, because the code then won't compile.
By name: the `excludeName` attribute
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(excludeName = {
"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration",
"org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration"
})
public class Application {
}excludeName takes fully qualified class names as strings. Use it when the class may not be on the classpath at compile time, such as an optional dependency. The cost is that the compiler cannot catch a misspelled name. A wrong name is silently ignored, because Spring only validates names it can load (see the failure modes below).
By property: `spring.autoconfigure.exclude`
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfigurationIn YAML, the same setting is a list:
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
- org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfigurationThe property is useful because it can differ per environment. You can set it in a profile-specific file such as application-local.properties, in a system property, or in the environment variable SPRING_AUTOCONFIGURE_EXCLUDE. It also keeps the exclusion out of your Java code.
When you use both the annotation and the property, Spring merges them. The final exclusion set is the union of exclude, excludeName, and the property values.
| Mechanism | Checked at compile time | Works if class may be absent | Can vary per environment |
|---|---|---|---|
| `exclude` | Yes | No | No |
| `excludeName` | No | Yes | No |
| `spring.autoconfigure.exclude` | No | Yes | Yes |
Where exclusion happens in the pipeline
The AutoConfigurationImportSelector builds the final list in a fixed sequence. Knowing the sequence explains most surprises.
Three consequences follow from this:
- An excluded class is removed before the early class and web-application filters. Its conditions are never evaluated, and it does not appear in the report as a negative match. It appears under
Exclusionsinstead. - Exclusion works on the candidate list. It does not touch classes that your own code imports or scans.
- Sorting happens after exclusion, so excluding a class cannot break the
beforeandafterconstraints of the others. The ordering rules simply ignore classes that are absent.
What happens to dependent beans
Excluding an auto-configuration removes every bean it would have defined. Other auto-configurations that depend on those beans react through their own conditions.
Take DataSourceAutoConfiguration. Excluding it means no DataSource bean exists unless you define one. Auto-configurations guarded by @ConditionalOnBean(DataSource.class) then back off. That is why the AuditAutoConfiguration from the earlier chapter, which has @ConditionalOnBean(DataSource.class), creates no AuditLogger in this setup.
The reverse also happens. Some classes need the bean and fail when it is missing. If you exclude DataSourceAutoConfiguration but keep HibernateJpaAutoConfiguration, the JPA setup may fail because it expects a data source. Exclude the related configurations together, or provide the beans yourself:
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Application {
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create()
.url("jdbc:h2:mem:demo")
.username("sa")
.password("")
.build();
}
}This example only works if an H2 driver is on the classpath. In most applications you would not exclude and re-create a data source like this. You would configure spring.datasource.* and let the auto-configuration build it. The code is here to show that exclusion plus your own bean is a valid pattern.
Verifying an exclusion
Run the application with --debug and look at the conditions evaluation report:
java -jar app.jar --debugThe report has an Exclusions section listing each excluded class. An excluded class does not appear in Positive matches or Negative matches. If you expected an exclusion and the class shows up under one of those sections, the exclusion did not take effect. Check the spelling of the name and where the property is defined.
You can also check in a test. This test starts the full application with the property set and asserts that no DataSource bean exists:
package com.example;
import static org.assertj.core.api.Assertions.assertThat;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest(properties = "spring.autoconfigure.exclude="
+ "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration")
class ExclusionTests {
@Autowired
private ApplicationContext context;
@Test
void dataSourceIsNotCreated() {
assertThat(this.context.getBeanNamesForType(DataSource.class)).isEmpty();
}
}Failure modes and gotchas
Excluding a class that is not an auto-configuration
Spring checks each excluded class that is present on the classpath. If it is not in the candidate list, startup fails with an IllegalStateException whose message says the classes "could not be excluded because they are not auto-configuration classes".
Typical causes:
- You tried to exclude one of your own
@Configurationclasses. Exclusion does not apply to classes found by component scanning or imported with@Import. Remove the scan, move the class out of the scanned package, or guard it with a condition. - You tried to exclude a nested class or a bean type instead of the auto-configuration class. For example, excluding
DataSource.classfails. You must nameDataSourceAutoConfiguration. - The class is an auto-configuration in a different version of the library, and the class has been renamed or moved. Upgrades are a common time for this error to appear.
Misspelled names are not always caught
The validation only covers classes that can be loaded. A name that matches no class on the classpath is ignored without an error, because the class might belong to an optional dependency. If an exclusion by name seems to have no effect, compare the name character by character with the one in the report.
Excluding too much
Excluding a high-level auto-configuration can hide a real problem instead of solving it. If the application fails because of a missing database URL, excluding DataSourceAutoConfiguration makes the error disappear, but code that injects a DataSource now fails later and less clearly. Ask first whether you need the dependency at all. Removing an unused starter from the build is cleaner than excluding what it brings in.
Exclusion and the test slices
Test slices such as @DataJpaTest import only the auto-configurations they need, so exclusions in your main application class still apply to the context. If a slice test behaves differently from the application, check whether your @SpringBootApplication exclusion is the cause. You can set the spring.autoconfigure.exclude property on the test to adjust it.
Choosing between exclusion and the alternatives
| Goal | Prefer |
|---|---|
| Replace one bean with your own | Define the bean. The auto-configuration's `@ConditionalOnMissingBean` backs off. |
| Switch a feature off | Use the feature's property, such as `greeting.enabled=false`, if it exists. |
| Remove a whole auto-configuration | `spring.autoconfigure.exclude` or `exclude` |
| Remove an unused feature for good | Remove the dependency from the build. |
Prefer the narrowest tool that works. A property or an own bean changes one behavior and keeps the rest. Exclusion removes everything the class would have contributed.
Exercise
Your application has spring-boot-starter-jdbc on the classpath for a later feature, but no database is configured yet, and startup fails because no DataSource URL is available. You want to fix this for the local profile only, without changing Java code. What do you add, and how do you confirm the exclusion took effect?
Show answer
Add spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration to application-local.properties and run with the local profile. Start the application with --debug and check that DataSourceAutoConfiguration is listed under Exclusions in the conditions evaluation report and does not appear under positive or negative matches.
Exercise
A teammate writes @SpringBootApplication(exclude = MyAppConfig.class) where MyAppConfig is a @Configuration class in the application's own package. The application fails at startup. Why, and what are two ways to fix it?
Show answer
MyAppConfig is not listed in an AutoConfiguration.imports file, so it is not an auto-configuration. Spring rejects the exclusion with an IllegalStateException saying the class could not be excluded because it is not an auto-configuration class. To fix it, either move the class out of the scanned packages (or remove the @Configuration annotation and stop importing it), or keep it and guard it with a condition such as @ConditionalOnProperty so it can be turned off.