Learnitweb

Auto-configuration and disable auto-configuration in Spring boot

1. Introduction

Auto-configuration of Spring Application Context automatically configures the beans which are likely to be needed in application development.

We use @EnableAutoConfiguration annotation for auto-configuration. We generally use @SpringBootApplication annotation in a Spring application, and this annotation enables the auto-configuration of the context automatically. So there is no additional use of using @EnableAutoConfiguration with @SpringBootApplication.

Auto-configuration classes are regular Spring @Configuration beans. Auto-configuration does help in configuration of the context and get us started quickly. Spring Boot tries to auto-configure the application context based on jars we provide in the classpath. For example, if HSQLDB dependency is in the classpath, Spring Boot will configure an in-memory database (if we don’t configure database connection beans manually).

2. Disabling auto-configuration in Spring Boot

We’ll see two ways to disable auto-configuration in Spring Boot:

  • Disable using annotation
  • Disable using property file

Disabling selective classes is very helpful while testing.

2.1 Disable auto-configuration using annotation

We can use exclude attribute of @SpringBootApplication to disable auto-configuration. For example, following code disables auto-configuration for Spring Data JPA:

@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class, 
    DataSourceTransactionManagerAutoConfiguration.class, 
    HibernateJpaAutoConfiguration.class
})

If the class is not on the classpath, we can use the excludeName attribute. We have to provide fully qualified class name in this case.

2.2 Disable using property file

If we don’t want to use annotation to exclude files, we can use spring.autoconfigure.exclude property. For example, following code disables auto-configuration for Spring Data JPA using spring.autoconfigure.exclude property.

spring.autoconfigure.exclude= \ 
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, \
  org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, \
  org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration

Conclusion

In this short tutorial, we discussed in brief about auto-configuration in Spring Boot and how to disable it. We discussed two ways to do it, annotation and property file. Auto-configuration is very useful and disabling auto-configuration is very handy while testing.