Spring源码之注解的原理
https://blog.csdn.net/qq_28802119/article/details/83573950
https://www.zhihu.com/question/318439660/answer/639644735
https://blog.csdn.net/u014534808/article/details/81071452
https://www.cnblogs.com/lxyit/p/10210581.html
https://www.cnblogs.com/lipengsheng-javaweb/p/12888842.html
https://www.zhihu.com/question/24401191
https://www.cnblogs.com/yangming1996/p/9295168.html(最好的一篇)
https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6(官网)
JDK注解原理
原理总结:所有的注解都继承了Annotation接口,而注解类什么的注解,属于类中attribute。被注解修饰的类,在运行时会生成一个代理类(RetentionPolicy.RUNTIME),重写继承而来所有方法,从而实现功能。
所有注解都继承了annotation,打开任意注解类,用jclasslib查看便能看到:
Access flags: 0x... [public interface abstract annotation]

而在这个继承Annotation的注解类上面的注解,则属于这个类的Attributes
属性表有以下几种:
RuntimeVisibleAnnotations:运行时可见的注解
RuntimeInVisibleAnnotations:运行时不可见的注解
RuntimeVisibleParameterAnnotations:运行时可见的方法参数注解
RuntimeInVisibleParameterAnnotations:运行时不可见的方法参数注解
AnnotationDefault:注解类元素的默认值
所以在Class.forName(name, false, clToUse)进行反射时,便能获取此类上面annotation属性
而当要去获取一个注解类实例时(如调用getAnnotation),便会生成一个代理类。重写其所有方法,包括 value 方法以及自定义接口从 Annotation 接口继承而来的方法
自定义注解类:
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface MyComponent {
}
测试类:
@MyComponent
public class AnnotationTest {
public static void main(String[] args) {
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
MyComponent annotation = AnnotationTest.class.getAnnotation(MyComponent.class);
System.out.println(annotation.annotationType());
}
}
生成的代理类:
public final class $Proxy0 extends Proxy implements Retention {
...
public final Class annotationType() throws {
try {
return (Class)super.h.invoke(this, m4, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final RetentionPolicy value() throws {
try {
return (RetentionPolicy)super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
...
}
public final class $Proxy1 extends Proxy implements MyComponent {
...
public final String test() throws {
try {
return (String)super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final Class annotationType() throws {
try {
return (Class)super.h.invoke(this, m4, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
...
}
@TODO: 为何生成两个代理类
Spring中注解
createApplicationContext()时registerDefaultFilters
调用链:
SpringApplication#run() --> SpringApplication#createApplicationContext() --> new AnnotationConfigServletWebServerApplicationContext() --> ClassPathBeanDefinitionScanner# --> ClassPathScanningCandidateComponentProvider#registerDefaultFilters()
在registerDefaultFilters中会注册默认两个includerFilters(Component和ManagedBean)
protected void registerDefaultFilters() {
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
try {
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
logger.trace("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
}
......
}
同样断点,可查看到会将ComponentScanAnnotationParser、AutoConfigurationExcludeFilter、TypeExcludeFilter加入excludeFilters
获取MetadataReader
调用链:
AbstractApplicationContext#refresh() --> AbstractApplicationContext#invokeBeanFactoryPostProcessors() --> PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors() --> PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors() --> ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()--> ConfigurationClassPostProcessor#processConfigBeanDefinitions() --> ConfigurationClassPostProcessor#parse() --> ConfigurationClassPostProcessor#processConfigurationClass() -->
ConfigurationClassParser#parse() -->
ConfigurationClassParser#doProcessConfigurationClass() -->
ComponentScanAnnotationParser#parse() --> ClassPathBeanDefinitionScanner#doScan() --> ClassPathScanningCandidateComponentProvider#findCandidateComponents() --> ClassPathScanningCandidateComponentProvider#scanCandidateComponents --> CachingMetadataReaderFactory#getMetadataReader() --> SimpleMetadataReaderFactory#getMetadataReader()--> SimpleMetadataReader# -->ClassReader#accept()
在ClassReader类中依赖ASM字节码库实现,通过反射获取类所有信息。注解信息在类的attribute中
/**
* Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this
* {@link ClassReader}.
*
* @param classVisitor the visitor that must visit this class.
* @param attributePrototypes prototypes of the attributes that must be parsed during the visit of
* the class. Any attribute whose type is not equal to the type of one the prototypes will not
* be parsed: its byte array value will be passed unchanged to the ClassWriter. <i>This may
* corrupt it if this value contains references to the constant pool, or has syntactic or
* semantic links with a class element that has been transformed by a class adapter between
* the reader and the writer</i>.
* @param parsingOptions the options to use to parse this class. One or more of {@link
* #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.
*/
@SuppressWarnings("deprecation")
public void accept(
final ClassVisitor classVisitor,
final Attribute[] attributePrototypes,
final int parsingOptions) {
......
// Visit the RuntimeVisibleAnnotations attribute.
if (runtimeVisibleAnnotationsOffset != 0) {
int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);
int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;
while (numAnnotations-- > 0) {
// Parse the type_index field.
String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);
currentAnnotationOffset += 2;
// Parse num_element_value_pairs and element_value_pairs and visit these values.
currentAnnotationOffset =
readElementValues(
classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true),
currentAnnotationOffset,
/* named = */ true,
charBuffer);
}
}
// Visit the RuntimeVisibleTypeAnnotations attribute.
if (runtimeVisibleTypeAnnotationsOffset != 0) {
int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);
int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;
while (numAnnotations-- > 0) {
// Parse the target_type, target_info and target_path fields.
currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);
// Parse the type_index field.
String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);
currentAnnotationOffset += 2;
// Parse num_element_value_pairs and element_value_pairs and visit these values.
currentAnnotationOffset =
readElementValues(
classVisitor.visitTypeAnnotation(
context.currentTypeAnnotationTarget,
context.currentTypeAnnotationTargetPath,
annotationDescriptor,
/* visible = */ true),
currentAnnotationOffset,
/* named = */ true,
charBuffer);
}
}
......
// Visit the end of the class.
classVisitor.visitEnd();
}
判断是否满足@Component条件
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
if (isCandidateComponent(metadataReader)) {
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
sbd.setSource(resource);
if (isCandidateComponent(sbd)) {
candidates.add(sbd);
}
}
不在excludeFilters,并且在includeFilters中
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return isConditionMatch(metadataReader);
}
}
return false;
}
/**
* Determine whether the given bean definition qualifies as candidate.
* <p>The default implementation checks whether the class is not an interface
* and not dependent on an enclosing class.
* <p>Can be overridden in subclasses.
* @param beanDefinition the bean definition to check
* @return whether the bean definition qualifies as a candidate component
*/
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotationMetadata metadata = beanDefinition.getMetadata();
return (metadata.isIndependent() && (metadata.isConcrete() ||
(metadata.isAbstract() && metadata.hasAnnotatedMethods(Lookup.class.getName()))));
}
@Inherite
https://www.jianshu.com/p/7f54e7250be3
类继承关系中@Inherited的作用
类继承关系中,子类会继承父类使用的注解中被@Inherited修饰的注解
接口继承关系中@Inherited的作用
接口继承关系中,子接口不会继承父接口中的任何注解,不管父接口中使用的注解有没有被@Inherited修饰
类实现接口关系中@Inherited的作用
类实现接口时不会继承任何接口中定义的注解
TODO
一种是编译期直接的扫描,一种是运行期反射
Spring源码之注解的原理的更多相关文章
- Spring源码系列 — 注解原理
前言 前文中主要介绍了Spring中处理BeanDefinition的扩展点,其中着重介绍BeanDefinitionParser方式的扩展.本篇文章承接该内容,详解Spring中如何利用BeanDe ...
- spring源码解析之AOP原理
一.准备工作 在这里我先简单记录下如何实现一个aop: AOP:[动态代理] 指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式: 1.导入aop模块:Spring AOP:(s ...
- Spring源码之注解扫描Component-scan
本文主要介绍Spring的component-scan标签,了解spring是如何实现扫描注解进行bean的注册,主要实现实在 NamespaceHandler, NamespaceHandlerSu ...
- Spring源码之@Configuration原理
总结 @Configuration注解的Bean,在BeanDefinition加载注册到IOC容器之后,进行postProcessBeanFactory处理时会进行CGLIB动态代理 将@Prope ...
- Spring源码学习
Spring源码学习--ClassPathXmlApplicationContext(一) spring源码学习--FileSystemXmlApplicationContext(二) spring源 ...
- Spring源码分析专题——目录
Spring源码分析专题 -- 阅读指引 IOC容器 Spring源码分析专题 -- IOC容器启动过程(上篇) Spring源码分析专题 -- IOC容器启动过程(中篇) Spring源码分析专题 ...
- Spring 源码分析之 bean 依赖注入原理(注入属性)
最近在研究Spring bean 生命周期相关知识点以及源码,所以打算写一篇 Spring bean生命周期相关的文章,但是整理过程中发现涉及的点太多而且又很复杂,很难在一篇文章中把Spri ...
- Spring 源码分析之 bean 实例化原理
本次主要想写spring bean的实例化相关的内容.创建spring bean 实例是spring bean 生命周期的第一阶段.bean 的生命周期主要有如下几个步骤: 创建bean的实例 给实例 ...
- Spring源码情操陶冶-AnnotationConfigBeanDefinitionParser注解配置解析器
本文承接前文Spring源码情操陶冶-自定义节点的解析,分析spring中的context:annotation-config节点如何被解析 源码概览 对BeanDefinitionParser接口的 ...
随机推荐
- MeteoInfoLab脚本示例:中尺度气旋散点图
全球长时间序列中尺度气旋数据(http://cioss.coas.oregonstate.edu/eddies/)有netCDF格式,散点数据类型,只有一个很大的维Nobs = 2590938.尝试读 ...
- Java常见的一些经典面试题(附答案解析)
前言: 我想每个程序员比较头疼的事情都是:工作拧螺丝,面试造火箭吧.但是又必须经历这个过程,尤其是弄不清面试官问的问题,如果你准备的不是很充分,会导致面试的时候手足无措.今天这篇文章是从已工作5年的程 ...
- Windows(WSL2) Linux子系统搭建Docker环境
摘要:本文主要介绍了如何再Windows(WSL2)中启用Linux系统中,并搭建Docker环境. WSL是适用于 Linux 的 Windows 子系统可让开发人员按原样运行 GNU/Linux ...
- 第二十五章 ansible基础
一.Ansible概述 1.什么是Ansible Ansible是一个自动化统一配置管理工具,自动化主要体现在Ansible集成了丰富模块以及功能组件,可以通过一个命令完成一系列的操作,进而能减少重复 ...
- tensorflow 出现KeyError: 'tulips\\8689672277_b289909f97_n.jpg'报错
在学习tensorflow基础教程-图像章节过程中,按照官网教程学习的时候出现了以下报错 一开始很迷茫,按着教程走怎么会这样呢 ,上网查资料也没找到找到,没办法,只好自己找原因,根据提示KeyErro ...
- APP打开(一)—以亲身经历谈APP注册登录
如果不是自己接手过这样的产品,我可能也很难相信,会有公司能够做出十四个注册页面的APP,将选站点.输账号.输密码.用户协议.用户权限等全部拆解成一个一个单独的页面来做,用户在注册的时候仿佛在攀登一座云 ...
- find for /f 分割字符串 bat
@Echo off::总用例数For /f "tokens=2" %%i in ('Type bat.txt^|Find "Ran"') do (Echo %% ...
- 论文解读《ImageNet Classification with Deep Convolutional Neural Networks》
这篇论文提出了AlexNet,奠定了深度学习在CV领域中的地位. 1. ReLu激活函数 2. Dropout 3. 数据增强 网络的架构如图所示 包含八个学习层:五个卷积神经网络和三个全连接网络,并 ...
- SpringBoot连接多数据源(HBASE,KUDU,ORACLE集成和开发库)
前提:1.连接hadoop需要本地安装 winutils.exe 并在程序指定,不然程序会报错 IOException: HADOOP_HOME or hadoop.home.dir are not ...
- Linux下如何使用X86 CPU的GPIO
目录 1.前言 2.linux pinctrl子系统 3. pin controller driver 4.手动构造device 1.前言 在arm嵌入式开发中,各个外设具有固定的物理地址,我们可以直 ...