【SpringBoot-注解】@SpringBootApplication

1.理解@SpringBootApplication

@SpringBootApplication被用于激活@EnableAutoConfiguration、@ComponentScan、@Configuration三个注解的特性。

其中:

  • @EnableAutoConfiguration 负责激活spring boot自动装配机制
  • @ComponentScan 负责激活@Component的扫描
  • @Configuration 负责声明被标注为配置类

可以说明@SpringBootApplication等同于@EnableAutoConfiguration、@ComponentScan、@Configuration

但是在2.0之后就有变化了

java 复制代码
@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 {}

@ComponentScan并没有使用默认值,而是添加了排除的TypeFilter实现:

java 复制代码
public class AutoConfigurationExcludeFilter implements TypeFilter, BeanClassLoaderAware
java 复制代码
public class TypeExcludeFilter implements TypeFilter, BeanFactoryAware {
  • TypeExcludeFilter:用于查找BeanFactory中已经注册的TypeExcludeFilterBean,作为贷利执行对象。

  • AutoConfigurationExcludeFilter:用于排除其他同时标注@Configuration和@EnableAutoConfiguration的类。

从SpringBoot1.4开始@SpringBootApplication注解就开始有变化了。@SpringBootApplication没有标注@Configuration,而改成了@SpringBootConfiguration,运行上没有差矣。

关系变为:

  • @SpringBootConfiguration
    • @Configuration
      • @Component

尽管@ComponentScan 关注与@Component,但是也看到@SpringBootConfiguration 属于多层级引用了@Component,所以也能够被scan到。

我们用到的@Service 、@Repository、@Controller都是属于 @Component的派生注解也叫Spring模式注解。

2.相关属性

java 复制代码
    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "nameGenerator"
    )
    Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;

可以看到属性都标注@AliasFor注解,它就是用于桥接其他注解的属性。@AliasFor注解能够将一个或多个注解的属性 别名 于某个注解中。

所以综上所述 @SpringBootApplication 是一个聚合注解,被我们标注在引导类上。

相关推荐
_一条咸鱼_4 小时前
揭秘 Android TextInputLayout:从源码深度剖析其使用原理
android·java·面试
_一条咸鱼_4 小时前
揭秘!Android VideoView 使用原理大起底
android·java·面试
_一条咸鱼_4 小时前
深度揭秘!Android TextView 使用原理全解析
android·java·面试
_一条咸鱼_4 小时前
深度剖析:Android Canvas 使用原理全揭秘
android·java·面试
_一条咸鱼_4 小时前
深度剖析!Android TextureView 使用原理全揭秘
android·java·面试
_一条咸鱼_4 小时前
揭秘!Android CheckBox 使用原理全解析
android·java·面试
_一条咸鱼_4 小时前
深度揭秘:Android Toolbar 使用原理的源码级剖析
android·java·面试
_一条咸鱼_4 小时前
揭秘 Java ArrayList:从源码深度剖析其使用原理
android·java·面试