18. Using the @SpringBootApplication annotation
许多Spring Boot开发者喜欢他们的应用程序使用自动配置,组件扫描(component-scan)和在application class
中定义额外的配置.
一个单独的@SpingBootApplication
注解可以实现以上三点
:
@EnableAutoConfiguration
:启用SringBoot的自动配置机制@ComponentScan
:在main application
应用程序所在的包启用@Component
Scan(扫描)@Configuration
:允许在上下文中注册额外的Beans或添加额外的配置类.
该
@SpringBootApplication
注解相当于使用默认属性情况下的@Configuration
,@EnableAutoConfiguration
和@ComponentScan
@SpringBootApplication还提供别名来定制@EnableAutoConfiguration和@ComponentScan的属性。
这些特性都不是强制性的,您可以选择用它所支持的任何特性来替换这个注释。例如,您可能不想在应用程序中使用组件扫描:
@Configuration
@EnableAutoConfiguration
@Import({ MyConfig.class, MyAnotherConfig.class })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在本例中,应用程序与任何其他Spring引导应用程序一样,只是没有自动检测到@ component - annoated
类,并且显式地导入了用户定义的bean(请参阅@Import
)。