@EnableAutoConfiguration Spring Boot Example

In this article, we will discuss the importance of the annotation @EnableAutoConfiguration with an example.

@EnableAutoConfiguration Annotation Overview

@EnableAutoConfiguration annotation tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added.
 
Since the spring-boot-starter-web dependency added to classpath leads to configuring Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
When using @SpringBootApplication annotation, the auto-configuration of the context is automatically enabled, and adding this annotation has, therefore, no additional effect.
 
The below diagram shows the internal implementation of @EnableAutoConfiguration :

@EnableAutoConfiguration Annotation Example

Let's add @EnableAutoConfiguration annotation to the Application class or Main class to enable an auto-configuration feature in the Spring boot project.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@EnableAutoConfiguration Annotation Optional Elements

  • Class<?>[] exclude - Exclude specific auto-configuration classes such that they will never be applied.
  • String[] excludeName - Exclude specific auto-configuration class names such that they will never be applied.

Disabling Specific Auto-configuration Classes

If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of @EnableAutoConfiguration to disable them, as shown in the following example:
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
We can use the excludeName attribute of the annotation and specify the fully qualified name instead.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@EnableAutoConfiguration(excludeName = {"org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration",
"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Learn Spring Boot on Spring Boot Toturial

Related Spring and Spring Boot Annotations

Comments