本文结合《Spring源码深度解析》来分析Spring 5.0.6版本的源代码。若有描述错误之处,欢迎指正。

之前我们讲解了从缓存中获取单例的过程,那么,如果缓存中不存在已经加载的单例bean就需要从头开始bean的加载过程了,而Spring使用getSingleton的重载方法实现bean的加载过程。

/**
* Return the (raw) singleton object registered under the given name,
* creating and registering a new one if none registered yet.
* @param beanName the name of the bean
* @param singletonFactory the ObjectFactory to lazily create the singleton
* with, if necessary
* @return the registered singleton object
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
// 全局变量需要同步
synchronized (this.singletonObjects) {
// 首先检査对应的bean是否已经加载过,因为singleton模式其实就是复用已创建的bean,所以这一步是必须的
Object singletonObject = this.singletonObjects.get(beanName);
// 如果为空才可以进行singleton的bean的初始化
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 初始化bean
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
// 加入缓存
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}

上述代码中其实是使用了回调方法,使得程序可以在单例创建的前后做一些准备及处理操作,而真正的获取单例bean的方法其实并不是在此方法中实现的,其实现逻辑是在ObjectFactory类型的实例singletonFactory中实现的。而这些准备及处理操作包括如下内容。

(1)检杳缓存是否己经加载过。

(2)若没有加载,则记录beanName的正在加载状态。

(3)加载单例前记录加载状态。

可能你会觉得beforeSingletonCreation方法是个空实现,里面没有任何逻辑,但其实不是, 这个函数中做了一个很重要的操作:记录加载状态,也就是通过this.singletonsCurrentlylnCreation.add(beanName)将当前正要创建的bean记录在缓存中,这样便可以对循环依赖进行检测。

/**
* Callback before singleton creation.
* <p>The default implementation register the singleton as currently in creation.
* @param beanName the name of the singleton about to be created
* @see #isSingletonCurrentlyInCreation
*/
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}

(4)通过调用参数传人的ObjectFactory的个体Object方法实例化bean。

(5)加载单例后的处理方法调用。

同步骤(3 )的记录加载状态相似,当bean加载结束后需要移除缓存中对该bean的正在加载状态的记录。

/**
* Callback after singleton creation.
* <p>The default implementation marks the singleton as not in creation anymore.
* @param beanName the name of the singleton that has been created
* @see #isSingletonCurrentlyInCreation
*/
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}

(6)将结果记录至缓存并删除加载bean过程中所记录的各种辅助状态。

/**
* Add the given singleton object to the singleton cache of this factory.
* <p>To be called for eager registration of singletons.
* @param beanName the name of the bean
* @param singletonObject the singleton object
*/
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}

(7)返回处理结果。

虽然我们已经从外部了解了加载bean的逻辑架构,但现在我们还并没有开始对bean加载功能的探索,之前提到过,bean的加载逻辑其实是在传人的ObjectFactory类型的参数 singletonFactory中定义的,我们反推参数的获取,得到如下代码:

sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});

ObjectFactory的核心部分其实只是调用了 createBean的方法,所以我们还需要到createBean 方法中追寻真理。

Spring源码分析(十五)获取单例的更多相关文章

  1. C# DateTime的11种构造函数 [Abp 源码分析]十五、自动审计记录 .Net 登陆的时候添加验证码 使用Topshelf开发Windows服务、记录日志 日常杂记——C#验证码 c#_生成图片式验证码 C# 利用SharpZipLib生成压缩包 Sql2012如何将远程服务器数据库及表、表结构、表数据导入本地数据库

    C# DateTime的11种构造函数   别的也不多说没直接贴代码 using System; using System.Collections.Generic; using System.Glob ...

  2. Vue.js 源码分析(十五) 指令篇 v-bind指令详解

    指令是Vue.js模板中最常用的一项功能,它带有前缀v-,比如上面说的v-if.v-html.v-pre等.指令的主要职责就是当其表达式的值改变时,相应的将某些行为应用到DOM上,先介绍v-bind指 ...

  3. Spring源码分析(五)获取Document

    摘要:本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. 这一篇开始进行Document加载了,XmlBeanFactoryRea ...

  4. jQuery 源码分析(十五) 数据操作模块 val详解

    jQuery的属性操作模块总共有4个部分,本篇说一下最后一个部分:val值的操作,也是属性操作里最简单的吧,只有一个API,如下: val(vlaue)        ;获取匹配元素集合中第一个元素的 ...

  5. ABP源码分析十五:ABP中的实用扩展方法

    类名 扩展的类型 方法名 参数 作用 XmlNodeExtensions XmlNode GetAttributeValueOrNull attributeName Gets an   attribu ...

  6. Heritrix源码分析(十五) 各种问题总结(转)

    开博客以及建立Heritrix 群有一段时间了(这里谢谢大家的关注),这篇博客将整理这段时间所遇到的问题.同时由于自己从今年5月份开始就不怎么接触Heritrix,很多东西开始遗忘(不过里面思想没忘) ...

  7. Heritrix源码分析(十五)

    开博客以及建立Heritrix 群有一段时间了(这里谢谢大家的关注),这篇博客将整理这段时间所遇到的问题.同时由于自己从今年5月份开始就不怎么接触Heritrix,很多东西开始遗忘(不过里面思想没忘) ...

  8. twisted 源码分析一:reactor 单例

    一个twisted进程只会有一个reactor反应器,下面我们来看看twisted是怎样实现这个单例反应器的, 路径:twisted\internet\reactor.py 主要代码如下: impor ...

  9. [Abp 源码分析]十五、自动审计记录

    0.简介 Abp 框架为我们自带了审计日志功能,审计日志可以方便地查看每次请求接口所耗的时间,能够帮助我们快速定位到某些性能有问题的接口.除此之外,审计日志信息还包含有每次调用接口时客户端请求的参数信 ...

  10. Spring源码分析(十八)创建bean

    本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. 目录 一.创建bean的实例 1. autowireConstructor 2 ...

随机推荐

  1. async 配合mysql

    async-db.js const mysql = require('mysql') const pool = mysql.createPool({ host : '127.0.0.1', user ...

  2. content_form.class.php文件不完整 解决方案

    玩phpcms的从多少会遇到这个问题,根据错误提示我们可以发现是由于content_form.class.php文件不完整导致的,网上有好多文章说是把这个文件用本地的替换掉就可 以了,但是只要一更新缓 ...

  3. 【代码笔记】iOS-archive保存图片到本地

    一,工程图: 二,代码: RootViewController.h #import <UIKit/UIKit.h> @interface RootViewController : UIVi ...

  4. Myeclipse使用过程配置汇总

    1.下载安装及破解方法 myeclipse2014专业版下载地址链接:https://pan.baidu.com/s/1i62YOGt 密码:nlqj    : 下载后安装到最后一步先不要打开软件,如 ...

  5. Android横、竖屏幕动态切换(layout-land 和layout-port)

    下面是一个例子程序: 1.首先通过以下语句设置Activity为无标题和全屏模式: // 设置为无标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); ...

  6. windows 命令行报错:file(s) not in client view

    今天在执行p4 sync命令时报错:File(s) not in client view,查找后发现其实是未连接上p4服务器.需要重新设置P4PORT=服务器地址  即可解决(参考链接:https:/ ...

  7. 关于 未在本地计算机上注册“VFPOLEDB.1” 的解决方案

    在很古老的时候猿们会使用 Microsoft Visual FoxPro(即Dbf)的数据库,用于对数据的存储,和Access类似,而且两者可以互转,可以把它当成数据文件,如Access数据(MDB) ...

  8. popup定位引擎popper.js介绍

    https://medium.com/@FezVrasta/popper-js-v1-5e8b3acd888c https://survivejs.com/blog/popper-interview/ ...

  9. bootstrap作为mixin库的应用模式

    Bootstrap作为一个非常流行的前端css框架,得到了非常多的应用.一般的使用方法都是直接download bootstrap.css,作为css文件引入到html的markup中,随后直接引用其 ...

  10. 关于easyUI

    <input class="easyui-combobox" id="s_dataDicName" data-options="panelHei ...