\@SpringBootApplication注解

3/26/2022 SpringSpring 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 {

    /**
     * 自动装配要排除的类,功能来自于 @EnableAutoConfiguration
     */
    @AliasFor(annotation = EnableAutoConfiguration.class)
    Class<?>[] exclude() default {};

    /**
     *  自动装配要排除的类名,功能来自于 @EnableAutoConfiguration
     */
    @AliasFor(annotation = EnableAutoConfiguration.class)
    String[] excludeName() default {};

    /**
     * 配置扫描的包,功能来自于 @ComponentScan
     */
    @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
    String[] scanBasePackages() default {};

    /**
     * 配置扫描的class,该class所在的包都会被扫描,功能来自于 @ComponentScan
     */
    @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
    Class<?>[] scanBasePackageClasses() default {};

    /**
     * 是否启用 @Bean 方法代理,功能来自于 @Configuration
     */
    @AliasFor(annotation = Configuration.class)
    boolean proxyBeanMethods() default true;

}

@SpringBootApplication是一个组合注解,包含了@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan 三个注解的功能,同时提供了一些属性配置,也是来自于以上3个注解;

  1. @SpringBootConfiguration 包含了Configuration注解的功能;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
    @AliasFor(annotation = Configuration.class)
    boolean proxyBeanMethods() default true;

}
  1. @EnableAutoConfiguration是开启自动装配的关键注解,其中标记了@AutoConfigurationPackage,会将被@SpringBootApplication标记的类所在的包,包装成BasePackages,然后注册到spring容器中;

    @EnableAutoConfiguration 还通过@Import注解向容器中引入了AutoConfigurationImportSelector,该类会将当前项目支持的自动配置类添加到spring容器中;

  2. @ComponentScan 定义了包扫描路径,其excludeFilters值可以用来排除类的扫描,springboot指定了TypeExcludeFilter,表明我们可以继承该类来自主定义排除的类 ;

    同时也指定了 AutoConfigurationExcludeFilter ,该Filter 可以用来排除自动配置类,也就是说,自动配置类不会进行包描述操作。

Last Updated: 3/25/2022, 5:35:18 PM