@SpringBootApplication annotation
1. Introduction
@SpringBootApplication
It is an annotation provided by Spring Boot, which is usually used on the startup class (main class). It is a combination of three annotations:
1.@Configuration
Indicates that this class is a configuration class, equivalent to an XML configuration file.
2.@EnableAutoConfiguration
Tell Spring Boot to start the automatic configuration function and automatically configure Spring applications based on dependencies, configurations, etc. under the classpath.
3.@ComponentScan
Start component scanning, scan the package and subpackages of the current class by default, and inject classes marked with annotations such as @Component, @Service, @Repository, @Controller, etc. into the Spring container.
2. Use
1. Specify the package to scan
By default,@SpringBootApplication
It will recursively scan all subpackage components from the package it is located (e.g.@Component
、@Service
、@Repository
、@Controller
、@Configuration
wait).
If there are some components in your project that are not@SpringBootApplication
In the sub-package of the package, you need to set it manuallyscanBasePackages
To specify the package path to scan.
Examples are as follows:
@SpringBootApplication(scanBasePackages = {"", ""}) public class MyApplication { public static void main(String[] args) { (, args); } }
Use scenarios
- Your startup class MyApplication is not in the package, such as it is in , while the system module and infrastructure module are in and , respectively. In this case, the default scan will not overwrite and you need to specify it manually
scanBasePackages
。 - You only want to scan some packages, not the entire project's package. This can reduce the scanning overhead during startup and improve performance.
Replenish
Use ${} to inject configuration property values as follows:
@SpringBootApplication(scanBasePackages = {"${-package}.server", "${-package}.module"}) public class MyApplication { public static void main(String[] args) { (, args); } }
The .yaml file is as follows:
demo: info: base-package:
Note:
Custom starter annotations with @AutoConfiguration without having to put its path into the scan path.
This is the article about Spring Boot annotation @SpringBootApplication's detailed explanation of the use of Spring BootApplication. For more related Spring Boot annotations @SpringBootApplication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!