Using the @SpringBootApplication Annotation

很多 Spring Boot 开发人员希望让他们的应用程序使用自动配置、组件扫描,并且能够在他们的“应用程序类”上定义额外的配置。一个 @SpringBootApplication 注释可用于启用这三个特性,即:

Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single @SpringBootApplication annotation can be used to enable those three features, that is:

  • @EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism

  • @ComponentScan: enable @Component scan on the package where the application is located (see the best practices)

  • @SpringBootConfiguration: enable registration of extra beans in the context or the import of additional configuration classes. An alternative to Spring’s standard @Configuration that aids configuration detection in your integration tests.

@SpringBootApplication 还提供别名以自定义 @EnableAutoConfiguration@ComponentScan 的属性。

@SpringBootApplication also provides aliases to customize the attributes of @EnableAutoConfiguration and @ComponentScan.

所有这些特性都是可选的,您可以选择用所启用的任一特性来替换此单一注释。例如,您可能不希望在应用程序中使用组件扫描或配置属性扫描:

None of these features are mandatory and you may choose to replace this single annotation by any of the features that it enables. For instance, you may not want to use component scan or configuration properties scan in your application: include-code::individualannotations/MyApplication[]

在此示例中,MyApplication 与其他任何 Spring Boot 应用程序类似,只是 @Component 注释的类和 @ConfigurationProperties 注释的类不会自动检测到,并且用户定义的 Bean 是显式导入的(参见 @Import)。

In this example, MyApplication is just like any other Spring Boot application except that @Component-annotated classes and @ConfigurationProperties-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see @Import).