Spring注解Component原理源码解析
在实际开发中,我们经常使用Spring的@Component、@Service、@Repository以及 @Controller等注解来实现bean托管给Spring容器管理。Spring是怎么样实现的呢?我们一起跟着源码看看整个过程吧!
照旧,先看调用时序图:
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}
Spring启动时,会去扫描指定包下的文件。
public void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
this.scanner.scan(basePackages);
}
对应时序图方法1,ClassPathBeanDefinitionScanner#scan。交给ClassPathBeanDefinitionScanner处理。
ClassPathBeanDefinitionScanner 初始化时设置了注解过滤器
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,Environment environment, @Nullable ResourceLoader resourceLoader) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
if (useDefaultFilters) {
// 注册注解过滤器
registerDefaultFilters();
}
setEnvironment(environment);
setResourceLoader(resourceLoader);
}
protected void registerDefaultFilters() {
// 添加Component类型
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));
}
catch (ClassNotFoundException ex) {
}
try {
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
}
catch (ClassNotFoundException ex) {
}
}
在includeFilters添加了Component,ManagedBean两种注解类型。后面用来过滤加载到的class文件是否需要交给Spring容器管理。
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
for (String basePackage : basePackages) {
// 扫描包下有Spring Component注解,并且生成BeanDefinition
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
// 设置scope,默认是singleton
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
// 生成代理类信息
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
// 注册到Spring容器
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
对应时序图方法2,ClassPathBeanDefinitionScanner#doScan。该方法对包下class文件解析,符合Spring容器管理的类生成BeanDefinition,并注册到容器中。
扫描包下的class文件,把有Component注解的封装BeanDefinition列表返回。
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
}
else {
return scanCandidateComponents(basePackage);
}
}
对应时序图方法3,ClassPathScanningCandidateComponentProvider#findCandidateComponents。
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
// classpath*:basePackage/**/*.class
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
// 获取 basePackage 包下的 .class 文件资源
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
for (Resource resource : resources) {
// 判断是否可读
if (resource.isReadable()) {
try {
// 获取.class文件类信息
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
if (isCandidateComponent(metadataReader)) {
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
sbd.setResource(resource);
sbd.setSource(resource);
if (isCandidateComponent(sbd)) {
candidates.add(sbd);
}
}
} catch (Throwable ex) {
throw new BeanDefinitionStoreException("Failed to read candidate component class: " + resource, ex);
}
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
对应时序图方法4,ClassPathScanningCandidateComponentProvider#scanCandidateComponents。
public MetadataReader getMetadataReader(Resource resource) throws IOException {
if (this.metadataReaderCache instanceof ConcurrentMap) {
// No synchronization necessary...
MetadataReader metadataReader = this.metadataReaderCache.get(resource);
if (metadataReader == null) {
// 获取.class类元信息
metadataReader = super.getMetadataReader(resource);
this.metadataReaderCache.put(resource, metadataReader);
}
return metadataReader;
}
else if (this.metadataReaderCache != null) {
synchronized (this.metadataReaderCache) {
MetadataReader metadataReader = this.metadataReaderCache.get(resource);
if (metadataReader == null) {
metadataReader = super.getMetadataReader(resource);
this.metadataReaderCache.put(resource, metadataReader);
}
return metadataReader;
}
}
else {
return super.getMetadataReader(resource);
}
}
对应时序图方法5,CachingMetadataReaderFactory#getMetadataReader。 super.getMetadataReader(resource) 调用的是 SimpleMetadataReaderFactory#getMetadataReader。
public MetadataReader getMetadataReader(Resource resource) throws IOException {
// 默认是SimpleMetadataReader实例
return new SimpleMetadataReader(resource, this.resourceLoader.getClassLoader());
}
SimpleMetadataReader(Resource resource, @Nullable ClassLoader classLoader) throws IOException {
// 加载.class文件
InputStream is = new BufferedInputStream(resource.getInputStream());
ClassReader classReader;
try {
classReader = new ClassReader(is);
}
catch (IllegalArgumentException ex) {
throw new NestedIOException("ASM ClassReader failed to parse class file - " +
"probably due to a new Java class file version that isn't supported yet: " + resource, ex);
}
finally {
is.close();
}
AnnotationMetadataReadingVisitor visitor = new AnnotationMetadataReadingVisitor(classLoader);
// 解析.class元信息
classReader.accept(visitor, ClassReader.SKIP_DEBUG);
this.annotationMetadata = visitor;
this.classMetadata = visitor;
this.resource = resource;
}
对应时序图方法6,SimpleMetadataReader#SimpleMetadataReader。 组装SimpleMetadataReader。
public void accept(
final ClassVisitor classVisitor,
final Attribute[] attributePrototypes,
final int parsingOptions) {
Context context = new Context();
context.attributePrototypes = attributePrototypes;
context.parsingOptions = parsingOptions;
context.charBuffer = new char[maxStringLength];
... 省略代码
// 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;
// 这里面封装Spring Component注解
currentAnnotationOffset =
readElementValues(classVisitor.visitAnnotation(annotationDescriptor,true),
currentAnnotationOffset,true,charBuffer);
}
}
... 省略代码
}
对应时序图方法7,ClassReader#accept。该方法把二进制的.class文件解析组装到AnnotationMetadataReadingVisitor
private int readElementValues(
final AnnotationVisitor annotationVisitor,
final int annotationOffset,
final boolean named,
final char[] charBuffer) {
... 省略代码
if (annotationVisitor != null) {
// 主要逻辑还在这里面
annotationVisitor.visitEnd();
}
return currentOffset;
}
对应时序图方法8,ClassReader#readElementValues。
public void visitEnd() {
super.visitEnd();
Class<? extends Annotation> annotationClass = this.attributes.annotationType();
if (annotationClass != null) {
... 省略代码
// 过滤java.lang.annotation包下的注解,及保留Spring注解
if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotationClass.getName())) {
try {
// 获取该类上的所有注解
Annotation[] metaAnnotations = annotationClass.getAnnotations();
if (!ObjectUtils.isEmpty(metaAnnotations)) {
Set<Annotation> visited = new LinkedHashSet<>();
for (Annotation metaAnnotation : metaAnnotations) {
// 过滤java.lang.annotation包下的注解,及保留Spring注解
recursivelyCollectMetaAnnotations(visited, metaAnnotation);
}
// 封装需要的注解
if (!visited.isEmpty()) {
Set<String> metaAnnotationTypeNames = new LinkedHashSet<>(visited.size());
for (Annotation ann : visited) {
metaAnnotationTypeNames.add(ann.annotationType().getName());
}
this.metaAnnotationMap.put(annotationClass.getName(), metaAnnotationTypeNames);
}
}
}
catch (Throwable ex) {
}
}
}
}
对应时序图方法9,AnnotationAttributesReadingVisitor#visitEnd。过滤掉 java.lang.annotation 包下的注解,然后把剩下的注解放到metaAnnotationMap。
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;
}
对应时序图方法10,ClassPathScanningCandidateComponentProvider#isCandidateComponent。使用前面提过的ClassPathBeanDefinitionScanner初始化时设置的注解类型过滤器,includeFilters 包含ManagedBean和Component类型。
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
if (matchSelf(metadataReader)) {
return true;
}
... 省略代码
return false;
}
对应时序图方法11,AbstractTypeHierarchyTraversingFilter#match。
protected boolean matchSelf(MetadataReader metadataReader) {
AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
return metadata.hasAnnotation(this.annotationType.getName()) ||
(this.considerMetaAnnotations && metadata.hasMetaAnnotation(this.annotationType.getName()));
}
对应时序图方法12,AnnotationTypeFilter#matchSelf。判断类的metadata中是否包含Component。
总结@Component到Spring bean容器管理过程。第一步,初始化时设置了Component类型过滤器;第二步,根据指定扫描包扫描.class文件,生成Resource对象;第三步、解析.class文件并注解归类,生成MetadataReader对象;第四步、使用第一步的注解过滤器过滤出有@Component类;第五步、生成BeanDefinition对象;第六步、把BeanDefinition注册到Spring容器。以上是@Component注解原理,@Service、@Controller和@Repository上都有@Component修饰,所以原理是一样的。
Spring注解Component原理源码解析的更多相关文章
- Spring Boot中@ConfigurationProperties注解实现原理源码解析
0. 开源项目推荐 Pepper Metrics是我与同事开发的一个开源工具(https://github.com/zrbcool/pepper-metrics),其通过收集jedis/mybatis ...
- 【Spring实战】Spring注解配置工作原理源码解析
一.背景知识 在[Spring实战]Spring容器初始化完成后执行初始化数据方法一文中说要分析其实现原理,于是就从源码中寻找答案,看源码容易跑偏,因此应当有个主线,或者带着问题.目标去看,这样才能最 ...
- 【转】【Spring实战】Spring注解配置工作原理源码解析
一.背景知识 在[Spring实战]Spring容器初始化完成后执行初始化数据方法一文中说要分析其实现原理,于是就从源码中寻找答案,看源码容易跑偏,因此应当有个主线,或者带着问题.目标去看,这样才能最 ...
- vue双向绑定原理源码解析
当我们学习angular或者vue的时候,其双向绑定为我们开发带来了诸多便捷,今天我们就来分析一下vue双向绑定的原理. 简易vue源码地址:https://github.com/maxlove123 ...
- 设计模式课程 设计模式精讲 8-8 单例设计模式-Enum枚举单例、原理源码解析以及反编译实战
1 课堂解析 2 代码演练 2.1 枚举类单例解决序列化破坏demo 2.2 枚举类单例解决序列化破坏原理 2.3 枚举类单例解决反射攻击demo 2.4 枚举类单例解决反射攻击原理 3 jad的使用 ...
- 从ReentrantLock详解AQS原理源码解析
数据结构 java.util.concurrent.locks.AbstractQueuedSynchronizer类中存在如下数据结构. // 链表结点 static final class Nod ...
- java基础(十八)----- java动态代理原理源码解析
关于Java中的动态代理,我们首先需要了解的是一种常用的设计模式--代理模式,而对于代理,根据创建代理类的时间点,又可以分为静态代理和动态代理. 静态代理 1.静态代理 静态代理:由程序员创建或特定工 ...
- Spring Boot自动装配原理源码分析
1.环境准备 使用IDEA Spring Initializr快速创建一个Spring Boot项目 添加一个Controller类 @RestController public class Hell ...
- Spring 注解@Component,@Service,@Controller,@Repository
Spring 注解@Component,@Service,@Controller,@RepositorySpring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释, ...
随机推荐
- css让文字,字母折行
加上如下的CSS设置,就是设定好宽度width,然后设置合适的word-wrap和word-break属性: ul li{ width: 100px; word-wrap: break-word; w ...
- 理清gcc、libc、libstdc++的关系
当你在linux下写C/C++代码的时候,是不是会遇到许多编译链接的问题? 时不时报个glibc,gcc,g++等相关的错误? 很多时候都无从下手,而且比较混乱. 这也是编译链接过程中经常出现的问题. ...
- [Shell]常用语法
赋值 FILE=$1 //=两边不能有空格 echo $FILE 逻辑判断 表达式 .if [ expression ]; then ... fi //[]两边必须有空格 . if [[ expres ...
- UVA 796 Critical Links —— (求割边(桥))
和求割点类似,只要把>=改成>即可.这里想解释一下的是,无向图没有重边,怎么可以使得low[v]=dfn[u]呢?只要它们之间再来一个点即可. 总感觉图论要很仔细地想啊- -一不小心就弄混 ...
- ImportError: DLL load failed: 找不到指定的模块
如果遇到错误:ImportError: DLL load failed: 找不到指定的模块出现错误原因:安装包的来源问题,也可以理解为包版本兼容问题,有的包使用官方出版,有的包使用whl文件安装 解决 ...
- MongoDB系列二:MongoDB安装过程
一.MongoDB安装,以Linux系统安装为例:(下载:www.mongodb.org 注意使用stable版本) 1.下载最新版本的MongoDB安装包,wget http://fastdl.mo ...
- 手把手教你设置MongoDB密码
mongodb密码和传统数据如mysql等有些区别: mongodb的用户名和密码是基于特定数据库的,而不是基于整个系统的.所有所有数据库db都需要设置密码. 1. 查看所有数据库(在mongodb新 ...
- linux基础技巧
命令行颜色显示: \[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\0 ...
- HearthBuddy遇奥秘解决方法
https://tieba.baidu.com/g/5808796816 链接: https://pan.baidu.com/s/1NPQTOfxbN_4alP7J-XWuVw 密码: xfj1
- 腾讯云安装mysql数据库
转载自 https://www.cnblogs.com/shalldou/p/10767043.html 首先,我们检测一下系统中是否已安装mysql的相关服务 命令: rpm -qa | grep ...