Spring Boot @EnableAutoConfiguration Annotation with Example - RameshMF/spring-boot-developers-guide GitHub Wiki
In this article, we will discuss important annotation of Spring Boot that is @EnableAutoConfiguration Annotation with an example.
@EnableAutoConfiguration annotation tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web dependency added to classpath leads to configure 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.
Let's add @EnableAutoConfiguration annotation to Application class or Main class to enable auto-configuration feature.
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);
}
}
- 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.
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);
}
}