文章目录
前言
使用Spring boot的同学都知道@SpringBootAppliaction是Spring boot 所有动作的核心,开启自动装配已以及类扫描都是在@SpringBootAppliaction中完成的,本文章主要是讨论@SpringBootAppliaction的一些知识点。
@SpringBootAppliaction 可以做些什么
在SpringBootAppliaction注解类中主要有五个需要关注的地方:1.@Inherited;2.@SpringBootConfiguration;3.@EnableAutoConfiguration;4.@ComponentScan;5.@AliasFor;这些注解赋予了@SpringBootAppliaction 各种能力。
1.@SpringBootAppliaction可继承性
我们新增一个@MySpringBootApplication使其继承@SpringBootAppliaction 然后在main方法类上使用项目可以正常启动
新增注解
注解使用
正常输出结果
2.@SpringBootAppliaction配置性
@SpringBootAppliaction使用@SpringBootConfiguration标注,然而@SpringBootConfiguration注解又是使用了@Configuration进行标注。
这也就为什么我们在main()方法的入口类中也能使用@Bean注解做bean 定义的原因。
3.开启自动装配
@SpringBootAppliaction注解使用@EnableAutoConfiguration注解标注,@EnableAutoConfiguration使用@Import注解将AutoConfigurationImportSelector.class加载DefaultListableBeanFactory容器中从而开启了自动装配功能(后面的章节做详细分析)。
4.过滤自动扫描的类
@SpringBootAppliaction注解上使用@ComponetScan注解的excludeFilters属性做了类的过滤操作,过滤的类为TypeExcludeFilter.class和AutoConfigurationExcludeFilter.class。为啥要过滤这两个类呢?
- TypeExcludeFilter
用于查找BeanFactory中已注册的TypeExcludeFilter Bean作为代理执行对象
- AutoConfigurationExcludeFilter
用于排除其它同时标注@Configuration和@EnableAutoConfiguation
5.注解整合
@SpringBootAppliaction注解通过@AliasFor注解将@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三个注解桥接整合。
@AliasFor属性别名,可以用作属性值传递,定义注解MyComponentScan2,使用packages值覆盖scanBasePackages值,最终输出结果:boot.code.common.annotation。
上面的案例是同一个注解中属性值别名,后面的案例是不同注解属性值传递,创建注解MyComponentScan,将MyComponentScan2#basePackages属性别名到MyComponentScan#scanBasePackages。
在类AliasDemo上标注@MyComponentScan2(basePackages = “boot.code.common.annotation”),使用AnnotatedElementUtils获取MyComponentScan注解值。
输出结果:boot.code.common.annotation
总结
本文主要讲解了@SpringBootAppliaction的一些动作,如@EnableAutoConfiguration开启注解的自动装备功能,@SpringBootConfiguration提供注解的配置功能,@ComponentScan提供类扫描功能,同时也演示了@AliasFor提供的属性别名功能,后面将做进一步的分析。