Most Spring Boot applications have a main class marked with @SpringBootApplication. This is a meta-annotation, which means it is composed of other annotations. Using it is the same as using these three annotations together:
- @SpringBootConfiguration
- @EnableAutoConfiguration
- @ComponentScan
Let's look at each of them quickly.
@SpringBootConfiguration
This is a specialized version of @Configuration. It marks the class as a place where bean definitions can be declared. Spring Boot can also find this class automatically (for example, when we run tests with @SpringBootTest).
@EnableAutoConfiguration
This annotation tells Spring Boot to configure beans for us automatically, based on the libraries we have on the classpath. For example, when the web starter is present, a web server is configured. It works in two steps:
- Load the list of auto-configuration classes. Spring Boot reads the class names from a text file called META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. This file is found inside the jar files on the classpath, and each line of it is the name of one auto-configuration class.
- Check the conditions. The auto-configuration classes use conditional annotations to decide if their beans should be registered. Some common ones are:
- @ConditionalOnClass: register the beans only if a given class is on the classpath.
- @ConditionalOnProperty: register the beans only if a given property has a given value.
- @ConditionalOnMissingBean: register the beans only if we have not defined our own bean of that type.
If a condition is not met, the beans are skipped.
Version note: before Spring Boot 2.7, the list of auto-configuration classes was kept in the META-INF/spring.factories file. Spring Boot 2.7 introduced the new .imports file. Since Spring Boot 3.0, the old spring.factories way is not supported for auto-configuration anymore.
@ComponentScan
This annotation scans the application for classes marked with @Component and registers them as beans. It also finds the annotations that are built on top of @Component, such as @Service, @Repository and @Controller.
The scan starts from the package of the main class and goes through all its sub-packages. So it is a good idea to keep the main class in the root package of the application. Classes outside that package are not found.
Summary
- @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
- @SpringBootConfiguration marks the class as a configuration class.
- @EnableAutoConfiguration loads the auto-configuration classes from the .imports file and keeps only those whose conditions are met.
- @ComponentScan finds our own @Component, @Service, @Repository and @Controller classes.
In the next tutorials, we will see each of these annotations with examples.
|