How to Disable Spring Data Auto-Configuration in Spring Boot
Learn how to disable Spring Data auto-configuration in Spring Boot 3.2.
20+ years shipping production Java in banking & fintech. Drawn from code that ran under real load.
- ✓Java 17+ (we use Java 21 in examples)
- ✓Spring Boot 3.2+ project with spring-boot-starter-data-jpa or spring-boot-starter-data-mongodb
- ✓Basic understanding of Spring Boot auto-configuration and @SpringBootApplication annotation
โข Use @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class}) โข Or set spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration in application.properties โข For fine-grained control, use @EnableJpaRepositories or @EnableMongoRepositories with explicit base packages โข Always check for transitive dependencies pulling in unwanted auto-configuration via Maven/Gradle dependency tree โข In production, use @ConditionalOnClass and @ConditionalOnMissingBean to conditionally disable auto-configuration
Think of Spring Boot's auto-configuration as a smart home assistant that turns on all the lights and appliances when you walk in. Sometimes, you don't want the coffee maker to start brewing because you're only there to grab a book. Disabling auto-configuration is like telling the assistant "hey, don't touch the coffee maker, I'll handle it myself."
Spring Boot's auto-configuration is a double-edged sword. On one hand, it saves you from writing boilerplate XML and Java config for common infrastructure like data sources, JPA repositories, and transaction managers. On the other hand, it can silently pull in dependencies you never asked for, causing classpath scanning nightmares and startup failures in production. I've seen this happen at 2 AM on a Black Friday sale when a seemingly innocent update to a shared library brought in HikariCP and MySQL driver into a service that was supposed to be a lightweight Redis cache layer. The result? Connection pool exhaustion, OOM kills, and a very angry VP of Engineering.
In this tutorial, we'll cover the exact mechanisms to disable Spring Data auto-configuration in Spring Boot 3.2. You'll learn the three main approaches: annotation-level exclusions, property-based exclusions, and conditional configuration. We'll also dive into production incidents where misconfigured auto-configuration caused data corruption and how to debug them using Spring Boot's auto-configuration report. By the end, you'll be able to confidently control which Spring Data modules (JPA, MongoDB, Redis, Cassandra, etc.) are auto-configured and which you manage manually.
Understanding Spring Boot Auto-Configuration for Data
Spring Boot's auto-configuration is driven by the @EnableAutoConfiguration annotation, which is meta-annotated on @SpringBootApplication. For Spring Data, it works by scanning the classpath for specific classes. If it finds javax.sql.DataSource, it configures a DataSource bean. If it finds org.springframework.data.jpa.repository.JpaRepository, it enables JPA repositories. This is powered by the spring.factories file in each auto-configuration JAR.
For example, spring-boot-autoconfigure-3.2.0.jar contains entries like: org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration
When your application starts, Spring Boot evaluates these auto-configuration classes conditionally using @ConditionalOnClass, @ConditionalOnMissingBean, and @ConditionalOnProperty annotations. This is why simply having a MySQL driver on the classpath can trigger DataSourceAutoConfiguration even if you intended to use it only for a test.
What the Official Docs Won't Tell You
The official Spring Boot documentation covers the basics of excluding auto-configuration, but it glosses over the subtle interactions between multiple auto-configuration classes. For instance, excluding DataSourceAutoConfiguration alone doesn't prevent JpaRepositoriesAutoConfiguration from trying to create a repository factory bean, which will fail because there's no DataSource. You often need to exclude multiple classes in a chain.
Another undocumented behavior: if you use @EnableJpaRepositories on a configuration class, it can still be overridden by auto-configuration if the auto-configuration class has a higher order. Spring Boot uses @AutoConfigureOrder to control precedence, and auto-configuration classes typically have order 0 (lowest precedence), but custom configurations can be overridden if they don't explicitly set @Order.
Also, the official docs don't emphasize that excluding auto-configuration via @SpringBootApplication only works for the primary application class. If you have multiple @Configuration classes, you need to use @EnableAutoConfiguration(exclude = ...) on each one, or use the global spring.autoconfigure.exclude property.
Using @EnableAutoConfiguration Exclusions
The most direct way to disable Spring Data auto-configuration is by using the exclude attribute on @EnableAutoConfiguration or its composed annotation @SpringBootApplication. This approach is compile-time safe because you reference the actual class objects, so any refactoring of auto-configuration class names will cause compilation errors.
For example, to disable all JPA-related auto-configuration: @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class})
You can also exclude by name using excludeName, which is useful when the auto-configuration class is not on the compile classpath (e.g., when using optional dependencies).
One common pitfall: if you exclude DataSourceAutoConfiguration but your code still references a DataSource bean (e.g., via @Autowired), Spring will throw a NoSuchBeanDefinitionException at startup. You must provide your own DataSource bean definition in a @Configuration class.
This approach is best for applications that need complete control over data access, such as when using a custom connection pool or a legacy ORM framework.
Property-Based Exclusion with spring.autoconfigure.exclude
For environment-specific exclusions, the spring.autoconfigure.exclude property is more flexible than compile-time annotations. You can set it in application.properties, application-{profile}.properties, or even as a command-line argument. This is particularly useful when you have different data access strategies for development, staging, and production.
For example, in development you might want to use an embedded H2 database with JPA auto-configuration, but in production you use a custom DataSource with manual configuration. You can exclude JPA auto-configuration only in the production profile.
The property accepts a comma-separated list of fully qualified class names. Spring Boot also supports a YAML list format: spring: autoconfigure: exclude: - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
One important nuance: property-based exclusions are processed after annotation-based exclusions. If both are specified, the union of all exclusions is applied. This can lead to double-exclusion warnings in the logs, but it's harmless.
However, there's a catch: if you mistype a class name in the property, Spring Boot silently ignores it. Always verify with the auto-configuration report that your exclusions are taking effect.
Conditional Configuration with @ConditionalOnClass and @ConditionalOnMissingBean
For advanced scenarios, you can create your own auto-configuration that conditionally disables Spring Data modules. This is useful when building shared libraries or frameworks that need to be compatible with multiple data access strategies.
Use @ConditionalOnClass to trigger your configuration only when a specific class is present. For example, you can create a configuration that only activates when both Redis and JPA are on the classpath, and then disable JPA repositories to avoid conflicts.
Use @ConditionalOnMissingBean to prevent duplicate bean definitions. If a user has already defined a DataSource bean, your auto-configuration should skip creating one.
Spring Boot also provides @AutoConfigureBefore and @AutoConfigureAfter to control ordering. For instance, you can ensure your custom configuration runs after the default auto-configuration and overrides it.
This approach requires deep understanding of Spring Boot's auto-configuration internals and is typically used by framework developers rather than application developers.
Disabling Specific Spring Data Modules (JPA, MongoDB, Redis, etc.)
Spring Boot supports multiple Spring Data modules. Each has its own auto-configuration class. Here are the key ones for Spring Boot 3.2:
- JPA: DataSourceAutoConfiguration, HibernateJpaAutoConfiguration, JpaRepositoriesAutoConfiguration
- MongoDB: MongoAutoConfiguration, MongoDataAutoConfiguration, MongoRepositoriesAutoConfiguration
- Redis: RedisAutoConfiguration, RedisRepositoriesAutoConfiguration
- Cassandra: CassandraAutoConfiguration, CassandraDataAutoConfiguration, CassandraRepositoriesAutoConfiguration
- Elasticsearch: ElasticsearchDataAutoConfiguration, ElasticsearchRepositoriesAutoConfiguration
To disable only MongoDB auto-configuration, for example: @SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
If you're using multiple data stores, you can selectively enable only the ones you need. For instance, a service that uses JPA for transactional data and Redis for caching should exclude MongoDB and Cassandra auto-configuration to avoid unnecessary beans.
One common mistake: excluding MongoAutoConfiguration but forgetting to exclude MongoRepositoriesAutoConfiguration. This results in repository beans being created without a MongoTemplate, causing late startup failures.
Debugging Auto-Configuration Issues in Production
When auto-configuration goes wrong in production, you need to diagnose quickly. Spring Boot provides several tools:
- Auto-configuration report: Enable by setting debug=true in application.properties or passing --debug as a VM argument. This prints a detailed report of all auto-configuration classes that matched, did not match, and were excluded.
- Actuator endpoint: If you have spring-boot-starter-actuator, the /actuator/conditions endpoint exposes the same information as JSON. This is invaluable for remote debugging.
- Beans endpoint: /actuator/beans shows all beans in the context, including their type and dependencies. Look for unexpected DataSource or EntityManagerFactory beans.
- Logging HTTP headers: Add logging.level.org.springframework.boot.autoconfigure=TRACE to see every condition evaluation in real-time.
In production, never use debug=true permanently as it prints sensitive configuration details. Instead, enable it temporarily via a management endpoint or use the actuator conditions endpoint with proper security.
Best Practices and Common Pitfalls
After years of dealing with auto-configuration issues, here are the practices that have saved my team countless hours:
- Always run the auto-configuration report in CI/CD: Add a step that starts the application with --debug and fails the build if unexpected auto-configuration classes match. This catches dependency drift early.
- Use a centralized exclusion list: In a microservices architecture, maintain a shared configuration library that defines common exclusions. This prevents each team from reinventing the wheel.
- Test exclusion scenarios: Write integration tests that verify certain auto-configuration classes are NOT present in the context. Use @SpringBootTest with specific profiles.
- Document exclusions: Add comments in application.properties or the main class explaining why each exclusion is needed. Future developers will thank you.
- Beware of @SpringBootApplication scanning: If you have multiple @Configuration classes, auto-configuration exclusions on the main class may not apply to all of them. Use @EnableAutoConfiguration on each configuration class that needs exclusions.
- Version compatibility: Auto-configuration class names can change between Spring Boot versions. Use your IDE's auto-complete to ensure you're referencing the correct classes for your version.
The Case of the Phantom DataSource: How Auto-Configuration Broke Our Payment Service
- Always run mvn dependency:tree or gradle dependencies to audit transitive dependencies before deploying to production.
- Use spring.autoconfigure.exclude in application.properties as a first line of defense for environment-specific exclusions.
- Enable auto-configuration report (debug=true) in staging to catch unexpected beans before they hit production.
curl -u admin:secret http://localhost:8080/actuator/conditions | jq '.contexts.application.positiveMatches | keys'mvn dependency:tree -Dincludes=*spring-boot-starter-data*| File | Command / Code | Purpose |
|---|---|---|
| AutoConfigDebug.java | @SpringBootApplication | Understanding Spring Boot Auto-Configuration for Data |
| ExcludeChainExample.java | @SpringBootApplication(exclude = { | What the Official Docs Won't Tell You |
| CustomDataSourceConfig.java | @Configuration | Using @EnableAutoConfiguration Exclusions |
| application-production.properties | spring.autoconfigure.exclude=\ | Property-Based Exclusion with spring.autoconfigure.exclude |
| CustomAutoConfiguration.java | @Configuration | Conditional Configuration with @ConditionalOnClass and @Cond |
| MultiDataStoreExclusion.java | @SpringBootApplication(exclude = { | Disabling Specific Spring Data Modules (JPA, MongoDB, Redis, |
| ActuatorConditions.java | management.endpoints.web.exposure.include=conditions,beans | Debugging Auto-Configuration Issues in Production |
| IntegrationTestExclusions.java | @SpringBootTest(properties = { | Best Practices and Common Pitfalls |
Key takeaways
Interview Questions on This Topic
How does Spring Boot's auto-configuration decide which beans to create?
Frequently Asked Questions
20+ years shipping production Java in banking & fintech. Drawn from code that ran under real load.
That's Spring Boot. Mark it forged?
5 min read · try the examples if you haven't