0、注解的定义
1、默认继承自Annotation
2、注解属于Class(注解,枚举,接口,类都是Class)
3、注解不能implement,extends
4、注解内只可以定义属性方法[不能定义接口中类似的普通方法],属性方法不能有参数,且返回值类型不能为void
5、注解内可以定义字段
6、注解的属性方法
7、注解的属性方法和字段可以被相应的注解修饰
1、自定义注解,一定要声明Retention
注解默认的保留时限是ClASS,即在类加载执行时注解就不会被保留。即通过运行时反射是获取不到注解信息的。
2、AnnotatedElement
注解A与其所修饰的元素E的关系:
- 直接存在 directly present
An annotation A is directly present on an element E if E has a RuntimeVisibleAnnotations or RuntimeVisibleParameterAnnotations or RuntimeVisibleTypeAnnotations attribute, and the attribute contains A.
简言之,注解A 是运行时注解,且直接修饰在元素E上。
- 间接存在 indirectly present
An annotation A is indirectly present on an element E if E has a RuntimeVisibleAnnotations or RuntimeVisibleParameterAnnotations or RuntimeVisibleTypeAnnotations attribute, and A 's type is repeatable, and the attribute contains exactly one annotation whose value element contains A and whose type is the containing annotation type of A 's type.
简言之,这是针对@Repeatable修饰的注解。
- 存在 present
A is directly present on E; or
No annotation of A 's type is directly present on E, and E is a class, and A 's type is inheritable, and A is present on the superclass of E.
简言之,即注解直接存在或者E是class,并且A是被@Inherited,且A修饰在E的父类上。即A存在E,A直接修饰E或者A修饰E的父类,且A是可继承的。
- 关联 associated
A is directly or indirectly present on E; or
No annotation of A 's type is directly or indirectly present on E, and E is a class, and A's type is inheritable, and A is associated with the superclass of E.
简言之,A直接或者间接的存在E,或者E是Class,A是可继承的,A不直接或间接存在E上,而是直接或者间接的存在E的父类上。
可以通过AnnotatedElement中定义的存取注解的方法获取E上不同类型的A。
3、元注解结构图
Spring注解体系结构
目前语言组织代码的方式大概可以分为三种:硬编码组件,配置文件组件,注解组织。每种组织都有他的体系结构。Spring的注解体系结构类似起配置文件,使用@Configuration代表配置文件,@Import @ImportResource导入其他配置文件,@Bean代表实例化bean,@Component代表组件,@Controller,@RestController @Service @Entity代表业务的子组件,是组件的分类而已,@ComponentScan代表扫描组件,@PropertySource注入占位符 这一系列的Spring的元注解定义了Spring的注解结构,也定义了他解析注解的基石。
SpringBoot的自配置完全是基于注解来拉起的,像@SpringBootApplication, @EnableWebMvc, @EnableCache这些不过是语法糖而已,用于组织某个模块的配置,使用这样的语法糖可以达到只引入一个配置就能拉起一个组件或模块的目的,很是便捷,像当与XML的针对一个第三方以来的配置。
Spring注解的解析器始于ConfigurationClassParser,而ConfigurationClassParser的调用始于AbstractApplicationContext的refresh方法对invokeBeanFactoryPostProcessors()的调用。注解的大致结构是先解析@Conditional,判断
解析条件是否满足,而后开始@Configuration @Component @Imported @ImportResource @PropertySources @ComponentScans @Bean 循环递归迭代达到从一点拉起全面的能力。