@SpringBootApplication 标注的类为 Spring Boot 的主配置类,Spring Boot 会运行这个类的 main 方法来启动 Spring Boot 应用。
@SpringBootApplication 注解的定义如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
@AliasFor(annotation = EnableAutoConfiguration.class)
String[] excludeName() default {};
/**
* Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
* for a type-safe alternative to String-based package names.
* @return base packages to scan
* @since 1.3.0
*/
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
/**
* Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
* scan for annotated components. The package of each class specified will be scanned.
* <p>
* Consider creating a special no-op marker class or interface in each package that
* serves no purpose other than being referenced by this attribute.
* @return base packages to scan
* @since 1.3.0
*/
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
}
说明
@SpringBootApplication 注解等价于以同时使 用 @SpringBootConfiguration,@EnableAutoConfiguration 和@ComponentScan 其中@SpringBootConfiguration 跟进去发现,其就等价于@Configuration,一个是在 Spring Boot 的名称,一起是在 Spring 中的名称。@Configuration 本质上也就是一个@Component,也是一个组件而已。
@EnableAutoConfiguration: 打开 Spring Boot 的自动配置机制 @ComponentScan: 允许程序自动扫描包,扫描当前包及其子包下标注了@Component,@Controller,@Service,@Repository 类并纳入到 spring 容器中进行管理。
@Configuration: @Configuration 标注的类能够被 Spring IoC 容器作为一个定义各种 bean 的配置源。
@SpringBootApplication 可以设置从指定的路径中扫描包,纳入 Spring 容器,也可以设置从 Spring 容器中排除某些类。通过如下几个属性实现:
Class<?>[] exclude() default {}: 根据 class 来排除, 排除特定的类加入 spring 容器,传入参数 value 类型是 class 类型。
String[] excludeName() default {}: 根据 class name 来排除, 排除特定的类加入 spring 容器,传入参数 value 类型是 class 的全类名字符串数组。
String[] scanBasePackages() default {}: 指定扫描包,参数是包名的字符串数组。如果想要注入的类,不属于当前@SpringBootApplication 标注类的子包下,就需要用这个属性手动设置需要扫描包的位置。
Class<?>[] scanBasePackageClasses() default {}: 扫描特定的包,参数类似是 Class 类型数组。