Back to Configuration & Profiles
Q4Question 4 of 5

How do you disable a specific auto-configuration in Spring Boot

Answer: You disable a specific auto-configuration in Spring Boot by adding its class to the exclude attribute of @SpringBootApplication or by setting spring.autoconfigure.exclude in application.properties.

Key Concepts
  • Use the exclude attribute of @SpringBootApplication or @EnableAutoConfiguration to disable specific auto-configuration classes at the annotation level.
  • Use the spring.autoconfigure.exclude property in application.properties or application.yml to disable auto-configurations without changing code.
  • The most common exclusion is DataSourceAutoConfiguration for services that do not use a database but have a JDBC driver on the classpath.
  • You can exclude multiple auto-configurations by listing them as a comma-separated string in the property or as an array in the annotation.
  • Excluding an auto-configuration that is not on the classpath throws an error unless you use excludeName with the fully qualified class name as a string.
  • Always check the CONDITIONS EVALUATION REPORT (debug=true) to verify that the exclusion worked and no unexpected beans remain.

Definition

You disable a specific auto-configuration in Spring Boot by adding its class to the exclude attribute of @SpringBootApplication or by setting spring.autoconfigure.exclude in application.properties.
  • exclude attribute is a parameter on @SpringBootApplication and @EnableAutoConfiguration that takes an array of auto-configuration classes to skip during startup.
  • excludeName attribute is the string-based version of exclude, used when the auto-configuration class might not be on the classpath (avoids compile-time dependency).
  • spring.autoconfigure.exclude is a property in application.properties or application.yml that lists fully qualified class names of auto-configurations to disable.
  • DataSourceAutoConfiguration is the most commonly excluded auto-configuration, disabled when a service has a JDBC driver on the classpath but does not use a database.
  • SecurityAutoConfiguration is often excluded in development or testing to disable the default Spring Security login page and password generation.

Think of National Bank of India ordering a branch setup package from headquarters. The package includes modules for everything: vault management, foreign exchange, insurance desk, ATM management. But this branch is a small loan-only office. The branch manager (developer) sends a note to headquarters: "exclude vault management and foreign exchange modules." The setup team skips those modules entirely, making the branch lighter and faster to set up. That note is the exclude attribute.

Understanding the Concepts

What does it mean to exclude an auto-configuration?

When you exclude an auto-configuration, Spring Boot skips that entire @Configuration class during startup. None of its @Bean methods are called, and none of its beans are created. This is useful when a library is on your classpath for a dependency, but you do not want its auto-configured beans.

JAVA
package com.bank;

public class ExcludeExplained {
    public static void main(String[] args) {
        System.out.println("Why exclude auto-configuration?");
        System.out.println("  1. JDBC driver on classpath (transitive dependency)");
        System.out.println("     but this service does not use a database");
        System.out.println("     -> exclude DataSourceAutoConfiguration");
        System.out.println();
        System.out.println("  2. Spring Security on classpath for a shared library");
        System.out.println("     but this service handles auth externally (API gateway)");
        System.out.println("     -> exclude SecurityAutoConfiguration");
        System.out.println();
        System.out.println("  3. JPA on classpath for a shared model jar");
        System.out.println("     but this service only calls REST APIs, no database");
        System.out.println("     -> exclude HibernateJpaAutoConfiguration");
    }
}
TEXT
Expected output:
Why exclude auto-configuration?
  1. JDBC driver on classpath (transitive dependency)
     but this service does not use a database
     -> exclude DataSourceAutoConfiguration

  2. Spring Security on classpath for a shared library
     but this service handles auth externally (API gateway)
     -> exclude SecurityAutoConfiguration

  3. JPA on classpath for a shared model jar
     but this service only calls REST APIs, no database
     -> exclude HibernateJpaAutoConfiguration

How do you exclude using the @SpringBootApplication annotation?

The exclude attribute accepts an array of auto-configuration classes. This is the most common and visible approach.

JAVA
package com.bank;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;

@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class
})
public class BankApiGatewayApp {
    public static void main(String[] args) {
        SpringApplication.run(BankApiGatewayApp.class, args);
        System.out.println("Application started without database auto-configuration");
    }
}
TEXT
Expected output:
Application started without database auto-configuration

No DataSource bean created.
No EntityManagerFactory bean created.
No TransactionManager bean created.

How do you exclude using application.properties?

The spring.autoconfigure.exclude property accepts a comma-separated list of fully qualified class names. This approach does not require code changes and works well with profiles.

PROPERTIES
# application.properties
spring.autoconfigure.exclude=\
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
JAVA
package com.bank;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BankNotificationService {
    public static void main(String[] args) {
        SpringApplication.run(BankNotificationService.class, args);
        System.out.println("Notification service started (no database)");
    }
}
TEXT
Expected output:
Notification service started (no database)

DataSourceAutoConfiguration excluded via application.properties.
No code change needed.

How is annotation exclude different from properties exclude?

Feature@SpringBootApplication(exclude)spring.autoconfigure.exclude
LocationJava codeapplication.properties
Compile-time checkYes (class reference)No (string, can typo)
Requires recompileYesNo
Profile-specificNo (unless combined with @Profile)Yes (application-dev.properties)
Multiple exclusionsArray in annotationComma-separated string
When class not on classpathCompile errorNo error (string is just ignored)
Best forPermanent exclusionsEnvironment-specific exclusions
JAVA
package com.bank;

public class ExcludeComparison {
    public static void main(String[] args) {
        System.out.println("Annotation exclude:");
        System.out.println("  @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)");
        System.out.println("  Compile-time safety: YES");
        System.out.println("  Requires recompile: YES");
        System.out.println();
        System.out.println("Properties exclude:");
        System.out.println("  spring.autoconfigure.exclude=...DataSourceAutoConfiguration");
        System.out.println("  Compile-time safety: NO");
        System.out.println("  Requires recompile: NO");
        System.out.println("  Can vary by profile: YES");
    }
}
TEXT
Expected output:
Annotation exclude:
  @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
  Compile-time safety: YES
  Requires recompile: YES

Properties exclude:
  spring.autoconfigure.exclude=...DataSourceAutoConfiguration
  Compile-time safety: NO
  Requires recompile: NO
  Can vary by profile: YES

What is a complete banking project that excludes auto-configuration?

This project is a banking notification service that sends SMS alerts. It has a JDBC driver on the classpath (from a shared internal library) but does not use a database. Without excluding DataSourceAutoConfiguration, Spring Boot would fail at startup because there is no database URL configured.

Project structure

DIAGRAM
bank-notification-service/
├── pom.xml
└── src/
    ├── main/
    │   ├── java/
    │   │   └── com/
    │   │       └── bank/
    │   │           ├── BankNotificationApp.java
    │   │           ├── service/
    │   │           │   └── SmsNotificationService.java
    │   │           └── controller/
    │   │               └── NotificationController.java
    │   └── resources/
    │       └── application.properties
    └── test/
        └── java/
            └── com/
                └── bank/
                    └── BankNotificationAppTest.java

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><parentsyn-kw">>
        syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
        syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
        syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
    syn-kw"></parentsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>bank-notification-servicesyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
    syn-kw"></propertiessyn-kw">>

    syn-kw"><dependenciessyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-websyn-kw"></artifactIdsyn-kw">>
        syn-kw"></dependencysyn-kw">>
        <!-- This pulls in JDBC driver transitively --syn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>com.h2databasesyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>h2syn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
    syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>

SmsNotificationService.java

JAVA
package com.bank.service;

import org.springframework.stereotype.Service;
import java.math.BigDecimal;

@Service
public class SmsNotificationService {

    public String sendPaymentAlert(String accountId, BigDecimal amount) {
        String message = "National Bank of India: Payment of "
            + amount + " INR processed for account " + accountId;
        System.out.println("SMS sent: " + message);
        return message;
    }

    public String sendBalanceAlert(String accountId, BigDecimal balance) {
        String message = "National Bank of India: Your balance is "
            + balance + " INR for account " + accountId;
        System.out.println("SMS sent: " + message);
        return message;
    }
}

NotificationController.java

JAVA
package com.bank.controller;

import com.bank.service.SmsNotificationService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Map;

@RestController
@RequestMapping("/api/notify")
public class NotificationController {

    private final SmsNotificationService smsService;

    public NotificationController(SmsNotificationService smsService) {
        this.smsService = smsService;
    }

    @GetMapping("/payment/{accountId}/{amount}")
    public Map<String, String> notifyPayment(
            @PathVariable String accountId,
            @PathVariable BigDecimal amount) {
        String result = smsService.sendPaymentAlert(accountId, amount);
        return Map.of("status", "sent", "message", result);
    }
}

BankNotificationApp.java

JAVA
package com.bank;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;

@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class
})
public class BankNotificationApp {
    public static void main(String[] args) {
        SpringApplication.run(BankNotificationApp.class, args);
    }
}

application.properties

PROPERTIES
server.port=8081

BankNotificationAppTest.java

JAVA
package com.bank;

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;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

@SpringBootTest
class BankNotificationAppTest {

    @Autowired
    private ApplicationContext context;

    @Test
    void dataSourceBeanNotPresent() {
        assertFalse(context.containsBean("dataSource"));
        assertTrue(context.containsBean("smsNotificationService"));
        System.out.println("Test passed: no DataSource, SmsNotificationService exists");
    }
}
TEXT
Expected output (application run):
  Started BankNotificationApp on port 8081
  (No DataSource configured, no database error)

Expected output (curl http://localhost:8081/api/notify/payment/SAV2001/50000):
{"status":"sent","message":"National Bank of India: Payment of 50000 INR processed for account SAV2001"}

How to run

BASH
cd bank-notification-service
mvn clean package -DskipTests
java -jar target/bank-notification-service-1.0.0.jar

# Test
curl http://localhost:8081/api/notify/payment/SAV2001/50000

# Run tests
mvn test

What are common mistakes when excluding auto-configuration?

Wrong: excluding the wrong class name

PROPERTIES
# application.properties
# WRONG: using the short name instead of fully qualified name
spring.autoconfigure.exclude=DataSourceAutoConfiguration
TEXT
Problem: Spring Boot looks for a class named "DataSourceAutoConfiguration" without a package.
It will not find it, and the auto-configuration is NOT excluded.
The app still tries to create a DataSource and fails.

Correct: use the fully qualified class name

PROPERTIES
# application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
TEXT
Correct: fully qualified class name.
Spring Boot finds and excludes the auto-configuration.

Wrong: forgetting to exclude related auto-configurations

JAVA
package com.bank;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class IncompleteExclusionApp {
    // Excluded DataSource, but DataSourceTransactionManagerAutoConfiguration
    // and HibernateJpaAutoConfiguration still try to run.
    // They may fail because there is no DataSource bean.
}
TEXT
Problem: related auto-configurations depend on DataSource.
Excluding only DataSourceAutoConfiguration may cause
DataSourceTransactionManagerAutoConfiguration to fail.
Exclude all related classes together.

Correct: exclude all related auto-configurations

JAVA
package com.bank;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;

@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class
})
public class CompleteExclusionApp {
    // All database-related auto-configurations excluded.
}
TEXT
Correct: all three database-related auto-configurations excluded.
No DataSource, no TransactionManager, no EntityManagerFactory created.
Application starts cleanly.

How do you verify the exclusion worked?

Use debug=true to see the CONDITIONS EVALUATION REPORT. Look for the excluded class in the "Exclusions" section.

JAVA
package com.bank;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class VerifyExclusionApp {
    public static void main(String[] args) {
        SpringApplication.run(VerifyExclusionApp.class, "--debug");
    }

    @Bean
    CommandLineRunner verify(ApplicationContext ctx) {
        return args -> {
            boolean hasDataSource = ctx.containsBean("dataSource");
            System.out.println("dataSource bean exists: " + hasDataSource);
            System.out.println("Exclusion verified: " + !hasDataSource);
        };
    }
}
TEXT
Expected output (in the CONDITIONS EVALUATION REPORT):
============================
Exclusions:
-----------
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

(in the CommandLineRunner output):
dataSource bean exists: false
Exclusion verified: true

What should a senior or principal engineer know?

  • excludeName for optional dependencies: use excludeName = "com.example.SomeAutoConfiguration" when the auto-configuration class might not be on the classpath. The string form avoids compile-time errors.
  • Profile-specific exclusions: put exclusions in profile-specific property files. For example, exclude SecurityAutoConfiguration only in application-dev.properties for local development.
  • Test slice exclusions: @WebMvcTest, @DataJpaTest, and other test slices already exclude unrelated auto-configurations. Adding manual exclusions on top can cause unexpected behavior.
  • Classpath optimization: instead of excluding, consider removing the unnecessary dependency from pom.xml. If a JDBC driver is a transitive dependency, use Maven's to remove it at the dependency level.
  • Auto-configuration report in Actuator: the /actuator/conditions endpoint provides the same information as debug=true, but as a JSON API. Enable it with management.endpoints.web.exposure.include=conditions.
JAVA
package com.bank.core;

public class SeniorExcludeKnowledge {
    public static void main(String[] args) {
        System.out.println("Senior/Principal Auto-Config Exclusion Checklist:");
        System.out.println("  1. excludeName for optional classpath dependencies (string form)");
        System.out.println("  2. Profile-specific exclusions in application-{profile}.properties");
        System.out.println("  3. Test slices already exclude unrelated auto-configs");
        System.out.println("  4. Prefer removing the dependency from pom.xml over excluding");
        System.out.println("  5. /actuator/conditions endpoint = JSON version of debug=true");
        System.out.println("  6. Always exclude related auto-configs together (DataSource + JPA)");
        System.out.println("  7. Verify with debug=true or the Exclusions section in the report");
    }
}
TEXT
Expected output:
Senior/Principal Auto-Config Exclusion Checklist:
  1. excludeName for optional classpath dependencies (string form)
  2. Profile-specific exclusions in application-{profile}.properties
  3. Test slices already exclude unrelated auto-configs
  4. Prefer removing the dependency from pom.xml over excluding
  5. /actuator/conditions endpoint = JSON version of debug=true
  6. Always exclude related auto-configs together (DataSource + JPA)
  7. Verify with debug=true or the Exclusions section in the report

What are common interview follow-up questions?

  • What happens if you exclude an auto-configuration that does not exist on the classpath? (With exclude = SomeClass.class, you get a compile error. With excludeName = "com.example.SomeClass", no error because it is a string.)
  • Can you exclude auto-configuration in a test? (Yes. Use @SpringBootTest with properties = "spring.autoconfigure.exclude=..." or use the exclude attribute on @TestConfiguration.)
  • What is the difference between excluding and providing your own bean? (Excluding skips the entire auto-configuration class. Providing your own bean uses @ConditionalOnMissingBean to back off just one bean while other beans from the same auto-configuration class may still be created.)
  • How do you find the class name of the auto-configuration to exclude? (Run with debug=true and look at the CONDITIONS EVALUATION REPORT. Or check the Spring Boot documentation for the list of auto-configuration classes.)
  • Can you exclude auto-configuration from a library jar? (Yes. The consumer application can exclude any auto-configuration using the annotation or properties approach, regardless of where the auto-configuration is defined.)

Visual Overview

DIAGRAM
 Three Ways to Exclude Auto-Configuration
 ==========================================

 Method 1: Annotation
 ┌────────────────────────────────────────────┐
 │ @SpringBootApplication(exclude = {         │
 │   DataSourceAutoConfiguration.class         │
 │ })                                          │
 │ Compile-time safe. Requires recompile.      │
 └────────────────────────────────────────────┘

 Method 2: Properties file
 ┌────────────────────────────────────────────┐
 │ spring.autoconfigure.exclude=               │
 │   org.springframework.boot.autoconfigure.   │
 │   jdbc.DataSourceAutoConfiguration          │
 │ No recompile. Can vary by profile.          │
 └────────────────────────────────────────────┘

 Method 3: excludeName (string form)
 ┌────────────────────────────────────────────┐
 │ @SpringBootApplication(excludeName = {      │
 │   "org.springframework.boot.autoconfigure." │
 │   + "jdbc.DataSourceAutoConfiguration"      │
 │ })                                          │
 │ No compile error if class not on classpath.  │
 └────────────────────────────────────────────┘


 Exclusion vs Back-Off
 ======================

 Exclusion (@SpringBootApplication exclude):
 ┌──────────────────────┐
 │ Auto-Config Class     │
 │  @Bean a()            │──▶ SKIPPED
 │  @Bean b()            │──▶ SKIPPED
 │  @Bean c()            │──▶ SKIPPED
 │  (entire class gone)  │
 └──────────────────────┘

 Back-Off (@ConditionalOnMissingBean):
 ┌──────────────────────┐
 │ Auto-Config Class     │
 │  @Bean a() -> user    │──▶ BACKED OFF (user defined a)
 │  @Bean b()            │──▶ CREATED
 │  @Bean c()            │──▶ CREATED
 │  (only a is skipped)  │
 └──────────────────────┘

Key Takeaway

Excluding auto-configuration is how you tell Spring Boot to skip beans you do not need. The most common case is a service that has a JDBC driver on the classpath as a transitive dependency but does not use a database. Without exclusion, Spring Boot tries to create a DataSource and fails because no database URL is configured.

You have three ways to exclude: the exclude attribute on @SpringBootApplication (compile-time safe), the spring.autoconfigure.exclude property (no recompile, works with profiles), and excludeName (string-based, safe when the class might not be on the classpath).

In our National Bank of India notification service, we excluded DataSourceAutoConfiguration, DataSourceTransactionManagerAutoConfiguration, and HibernateJpaAutoConfiguration. The service only sends SMS alerts and has no database. Without the exclusions, it would fail at startup.

The important distinction is between exclusion and back-off. Exclusion removes the entire auto-configuration class and all its beans. Back-off (@ConditionalOnMissingBean) skips only the specific bean that you have defined your own version of, while other beans from the same auto-configuration class are still created.

At the senior level, prefer removing the unnecessary dependency from pom.xml over excluding the auto-configuration. Use debug=true or the /actuator/conditions endpoint to verify that exclusions are working correctly.

Remember one sentence: use @SpringBootApplication(exclude) for compile-safe permanent exclusions and spring.autoconfigure.exclude for profile-specific exclusions, and always exclude related auto-configurations together.

---

Share
Use ← → arrow keys to navigate