Enabling Spring Boot auto-configuration
Spring Boot provides the @EnableAutoConfiguration annotation that is responsible for enabling the auto-configuration feature. This annotation is used in the main application file of the Spring Boot application. The @EnableAutoConfiguration annotation on a Spring Java configuration class causes Spring Boot to automatically create beans it thinks you need, usually based on classpath contents, that it can easily override.
Let's see the following code that represents the main application launcher class in the Spring Boot application:
@Configuration @EnableAutoConfiguration public class MyAppConfig { public static void main(String[] args) { SpringApplication.run(MyAppConfig.class, args); } }
But, Spring Boot also provides a shortcut for this configuration file by using another annotation, @SpringBootApplication.
It is very common to use @EnableAutoConfiguration, @Configuration, and @ComponentScan together. Let's see the following updated code:
@SpringBootApplication public class MyAppConfig { public static void main(String[] args) { SpringApplication.run(MyAppConfig.class, args); } }
In this code, @ComponentScan, with no arguments, scans the current package and its sub-packages.
@SpringBootApplication has been available since Spring Boot 1.2.
Let's see the following diagram to explain it better than the code:
In this diagram, we can say that the @SpringBootApplication annotation has composed functionality from three annotations—@EnableAutoConfiguration, @ComponentScan, and @Configuration.
Spring Boot Starter reduces a build's dependencies and Spring Boot auto-configuration reduces the Spring configuration.
If you want to exclude auto-configuration for some of the modules, then you use the exclude property of @SpringBootAnnotation. Let's look at the following code:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class MyAppConfig { ... }
As you can see in the code, this Spring Boot application will consider DataSourceAutoConfiguration.class and HibernateJpaAutoConfiguration.class for the auto-configuration.
Let's see the following diagram that explains all about the Spring Boot auto-configuration feature:
As you can see in the diagram, you just include the required modules in your Spring application. At runtime, Spring Boot checks libraries at the classpath of your application. If the required libraries are available on the classpath of your application, then Spring Boot configures the required beans and other configuration for your application. You don't need to worry about the configuration of the modules in the Spring Boot application.
Let's discuss another key component, Spring Boot CLI, in the next section.