Spring版本:
<version>5.2.1.RELEASE</version>
上一篇:16-Spring源码解析之Bean的生命周期(1)——doGetBean
上一篇我们介绍了doGetBean
包含的功能,在【功能八】中,doGetBean
会根据Bean
的scope
类型进行Bean
的加载。因为当前是Spring
容器的创建,因此程序走到这一步的时候,创建的Bean
是singleton
类型的。我再贴一下doGetBean
中【功能八】的代码:
if (mbd.isSingleton()) {
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;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
那么我们就进入getSingleton
方法中一探究竟吧。
一、getSingleton
获取单例
在上一篇文章的2.3.2节
也调用了getSingleton
方法,只是那时候是从缓存中获取单例,那么如果缓存中不存在当前的Bean
,我们就需要从头开始加载Bean
了,而Spring
就是使用了getSingleton
方法实现Bean
的加载的。记得上一篇文章2.3.2节
中提到的getSingleton
的几种重载方法吗?忘记了不要紧,我再在这里贴一下:
上一篇在缓存中获取单例的时候,调用的两个getSingleton
方法分别是:
public Object getSingleton(String beanName)
方法protected Object getSingleton(String beanName, boolean allowEarlyReference)
方法
而我们从头开始加载Bean
调用的getSingleton
为:
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory)
接下来,我们就要看一下Spring
是如何通过getSingleton
来创建Bean
的了,我们进入getSingleton
方法
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
//-----------------------------------【功能一】-----------------------------------
// 又检查了一次缓存中是否已经加载过名字为beanName的Bean
// 如果没有加载过,下面开始加载
// 如果加载过,就直接返回缓存中该的Bean
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// 如果这个Bean正在被销毁,就抛异常
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 + "'");
}
//-----------------------------------【功能二】--1.1 详细分析---------------------------------
// 加载单例bean之前记录加载状态
beforeSingletonCreation(beanName);
boolean newSingleton = false;
// 记录异常的异常链
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
//-----------------------------------【功能三】--1.4 详细分析---------------------------------
try {
// 创建Bean
singletonObject = singletonFactory.getObject();
// 设置标志位
newSingleton = true;
}
catch (