基于注解的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 先通过反 ...
随机推荐
- 2015年传智播客JavaEE 第168期就业班视频教程14-登录功能需求分析+模块结构命名规范
得先造一个模块,来封装我们的员工模型.登录的就是我们的员工嘛.员工模块属于权限校验系列的,校验叫做auth.进销存模块叫做cn.itcast.erp.invoice.权限模块叫做cn.itcast.e ...
- nSum “已知target再求和”类型题目总结:n-2重循环+left/right
Sum类的题目一般这样: input: nums[], target output: satisfied arrays/ lists/ number 拿到题目,首先分析: 1. 是几个数的sum 2. ...
- udp调优经验
降低丢包率: 1. 增大输入输出缓冲区 2. 调用发送接口时增大单次发送的buffer大小 8k 3. 多个socket 多线程接收 4 发送端流量控制,并且保证发送速率均匀 降低时延: 减小包大小? ...
- mybatis开发Dao的Mapper动态代理方式
1. 开发规范Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体跟Dao原始方法中接口实现类的方法相 ...
- 配置Linux防火墙
配置防火墙(服务器安全优化)(转) 安全规划:开启 80 22 端口并 打开回路(回环地址 127.0.0.1) # iptables –P INPUT ACCEPT # iptables –P O ...
- cmake 及make 实践记录
DEBIAN操作系统 预备操作: 安装 gcc g++ make cmake 开启Terminal 切换到超级用户 下载安装上述软件 A@debian:~$ su Password: root@deb ...
- mysql查询今天、昨天、近7天、近30天、本月、上一月的SQL语句
mysql查询今天.昨天.近7天.近30天.本月.上一月的SQL语句 这篇文章主要介绍了mysql查询今天.昨天.近7天.近30天.本月.上一月的SQL语句,一般在一些统计报表中比较常用这个时间段,需 ...
- cron.c
/* $OpenBSD: cron.c,v 1.39 2007/02/18 23:59:03 jmc Exp $ */ /* Copyright 1988,1990,1993,1994 by Paul ...
- I-Keyboard
SPOJ Problem Set (classical) 14. I-Keyboard Problem code: IKEYB Most of you have probably tried to t ...
- 企业搜索引擎开发之连接器connector(二十六)
连接器通过监视器对象DocumentSnapshotRepositoryMonitor从上文提到的仓库对象SnapshotRepository(数据库仓库为DBSnapshotRepository)中 ...