基于注解的Spring容器源码分析
从spring3.0版本引入注解容器类之后,Spring注解的使用就变得异常的广泛起来,到如今流行的SpringBoot中,几乎是全部使用了注解。Spring的常用注解有很多,有@Bean,@Compont,@Autowired等。这些注解的使用和基于xml文件的使用的方式如出一辙,只是一个是用注解一个是用配置文件而已。那么要学习Spring注解的原理,那么我们就得从基于注解spring容器类AnnotationConfigApplicationContext开始,接下来我们来分析:
第一步:看他的构造器
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
//给定一个beanFactory
public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
//用一个被注解的类创建一个AnonotationConfigApplicationContext
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
//扫描包名及子包类的被注解的类
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}
第二步:实际分析,我们构造一个AnnotationConfigApplicationContext对象,内部会做什么具体的操作。
我写了一个测试类,代码如下:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyBeanConfig.class);
他调用的构造器是这个:
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//初始化了AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner
this();
//注册类
register(annotatedClasses);
//刷新
refresh();
}
重点就是register方法和refresh方法分别都做了什么。
先来看register方法,点进去之后的代码如下:
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
//用于分析我传入的类的注解的信息
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
//Supplier有返回值无参数的接口
abd.setInstanceSupplier(instanceSupplier);
//检查scope,实例中没有指定,默认是singleton
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
//获取bean的名字,实例中这里是MyBeanConfig
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
//对于是否是@lazy,是否使用了@primary
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
//是否使用了@qualifier
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
} BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
//根据Bean的作用域,创建相应的代理对象
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
//将Bean加入到beanDefinitionMap中
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
到这里register方法就介绍完了。
然后看refresh方法:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 刷新前的准备
prepareRefresh();
// 创建并获取一个beanFanctory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 使用beanfactory之前的准备
prepareBeanFactory(beanFactory);
try {
//给子类实现用的,默认是空方法
postProcessBeanFactory(beanFactory);
//执行beanfactory的后处理
invokeBeanFactoryPostProcessors(beanFactory);
// 注册BeanPostProcessor,对bean进行初始化的前后可以调用
registerBeanPostProcessors(beanFactory);
// 初始化MessageSource
initMessageSource();
// 初始化application事件派发器
initApplicationEventMulticaster();
// 预留给子类来实现
onRefresh();
// 添加application监听器
registerListeners();
//初始化最后所有剩下的单实例bean
finishBeanFactoryInitialization(beanFactory);
// 完成bean和beanfactory初始化。
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
所有的bean都放入到了容器中了。还有部分内容不准确不详尽,等以后埋坑。。。
基于注解的Spring容器源码分析的更多相关文章
- Spring IoC 源码分析 (基于注解) 之 包扫描
在上篇文章Spring IoC 源码分析 (基于注解) 一我们分析到,我们通过AnnotationConfigApplicationContext类传入一个包路径启动Spring之后,会首先初始化包扫 ...
- Spring IOC 容器源码分析 - 获取单例 bean
1. 简介 为了写 Spring IOC 容器源码分析系列的文章,我特地写了一篇 Spring IOC 容器的导读文章.在导读一文中,我介绍了 Spring 的一些特性以及阅读 Spring 源码的一 ...
- Spring IOC 容器源码分析
声明!非原创,本文出处 Spring 最重要的概念是 IOC 和 AOP,本篇文章其实就是要带领大家来分析下 Spring 的 IOC 容器.既然大家平时都要用到 Spring,怎么可以不好好了解 S ...
- Spring IOC 容器源码分析(转)
原文地址 Spring 最重要的概念是 IOC 和 AOP,本篇文章其实就是要带领大家来分析下 Spring 的 IOC 容器.既然大家平时都要用到 Spring,怎么可以不好好了解 Spring 呢 ...
- Spring AOP源码分析(三):基于JDK动态代理和CGLIB创建代理对象的实现原理
AOP代理对象的创建 AOP相关的代理对象的创建主要在applyBeanPostProcessorsBeforeInstantiation方法实现: protected Object applyBea ...
- Spring IOC容器源码分析
注:本文转自https://javadoop.com/post/spring-ioc Spring 最重要的概念是 IOC 和 AOP,本篇文章其实就是要带领大家来分析下 Spring 的 IOC 容 ...
- 精尽Spring Boot源码分析 - 内嵌Tomcat容器的实现
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- Spring Ioc源码分析系列--容器实例化Bean的四种方法
Spring Ioc源码分析系列--实例化Bean的几种方法 前言 前面的文章Spring Ioc源码分析系列--Bean实例化过程(二)在讲解到bean真正通过那些方式实例化出来的时候,并没有继续分 ...
- Spring IOC 容器源码分析 - 填充属性到 bean 原始对象
1. 简介 本篇文章,我们来一起了解一下 Spring 是如何将配置文件中的属性值填充到 bean 对象中的.我在前面几篇文章中介绍过 Spring 创建 bean 的流程,即 Spring 先通过反 ...
随机推荐
- Go Methods and Interfaces
[Go Methods and Interfaces] 1.Go does not have classes. However, you can define methods on struct ty ...
- ubuntu ibus&language 启动失败
[ubuntu ibus&language 启动失败] 版本:ubuntu 10.04 现像:language support & ibus 无法启动,导致无法使用中文输入法 原因:l ...
- Redhat安装python环境(readline模块)
多次尝试,发现linux下安装软件: yum install readline-devel readline patch yum update python -y # 这步很重要,修复了报错 pip3 ...
- Python服务器开发 -- 网络基础-乾颐堂
网络由下往上分为物理层.数据链路层.网络层.传输层.会话层.表示层和应用层. HTTP是高层协议,而TCP/IP是个协议集,包过许多的子协议.包括:传输层的 FTP,UDP,TCP协议等,网络层的ip ...
- qt5.7 安装
http://blog.csdn.net/liang19890820/article/details/53931813#安装-qt57 安装运行出错:qt vstool 指定qt安装路径 http:/ ...
- Zookeeper 源码(三)Zookeeper 客户端源码
Zookeeper 源码(三)Zookeeper 客户端源码 Zookeeper 客户端主要有以下几个重要的组件.客户端会话创建可以分为三个阶段:一是初始化阶段.二是会话创建阶段.三是响应处理阶段. ...
- DataStage 七、在DS中使用配置文件分配资源
DataStage序列文章 DataStage 一.安装 DataStage 二.InfoSphere Information Server进程的启动和停止 DataStage 三.配置ODBC Da ...
- Imageloader、Glide、Fresco的性能及加载速度比较
一.使用方式: // 下面两个依赖包可选,根据需求二选一即可, compile 'com.ladingwu.library:fresco:0.0.9' compile 'com.la ...
- R语言中 fitted()和predict()的区别
fitted是拟合值,predict是预测值.模型是基于给定样本的值建立的,在这些给定样本上做预测就是拟合.在新样本上做预测就是预测. 你可以找一组数据试试,结果如何. fit<-lm(weig ...
- UVa 10603 Fill (暴力BFS+优先队列)
题意:给定4个数,a,b,c,d,分别代表空杯子容积为a,b,一个盛满水的杯子容积为c,让你不断倒水,找一个dd,是不是存在某个时刻, 某个杯子里的水dd,和d相同,或者无限接近.让求最少的倒水量和d ...