Spring Boot auto-configuration automatically creates and configures beans based on the libraries available in the application's classpath. In some scenarios, we may want to disable a particular auto-configuration to avoid unnecessary bean creation or to use our own custom configuration.
Key Points: • Specific auto-configurations can be disabled using the exclude attribute of @SpringBootApplication. • Auto-configuration can also be disabled using the spring.autoconfigure.exclude property. • Disabling unnecessary auto-configurations can improve startup time and avoid bean conflicts.
Example: Suppose an application includes the JPA dependency but does not require a database connection.
Spring Boot will automatically attempt to configure:
• DataSource • EntityManager • TransactionManager
Since no database configuration exists, the application startup may fail.
In such cases, disabling DataSource auto-configuration solves the problem.
Code Example:
@SpringBootApplication(
exclude = {
DataSourceAutoConfiguration.class
}
)
public class Application {
public static void main(String[] args) {
SpringApplication.run(
Application.class, args);
}
}Alternative Approach:
application.properties
spring.autoconfigure.exclude=\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationThis disables the auto-configuration without modifying Java code.
Common Auto-Configurations That Are Disabled:
• DataSourceAutoConfiguration • SecurityAutoConfiguration • RedisAutoConfiguration • MongoAutoConfiguration • RabbitAutoConfiguration
Real-World Example:
Batch Processing Application:
• Uses file processing only. • Does not require a database.
Disabling DataSourceAutoConfiguration:
• Reduces startup time. • Prevents unnecessary bean creation. • Eliminates configuration errors.
Why Disable Auto-Configuration?
• To avoid unwanted bean initialization. • To replace default configuration with custom implementation. • To improve application startup performance. • To resolve bean conflicts in complex applications.
Interview Tip: A concise interview answer is: To disable a specific auto-configuration in Spring Boot, I use the exclude attribute of @SpringBootApplication or the spring.autoconfigure.exclude property. This prevents Spring Boot from creating unwanted beans and allows custom configurations to take precedence.