在之前的小节中已经分析了spring中的一些基本用法,xml解析,注册BeanDefinition等过程,IoC容器已经完成了初始化工作,但是bean却是我们第一次向IoC容器索取bean时才会被实例化,且根据bean的作用域如果bean的类型是单例bean的话,IoC容器会缓存该bean的实例,今天我们就来分析Spring从缓存中获取单例bean。
引言
我们知道对于单例bean,Spring在创建bean之后都会缓存bean的实例,以供下次使用,那么这些bean被缓存到哪里了呢?打开DefaultSingletonBeanRegistry
,可以发现该类中有很多Map和Set的缓存,这些缓存都代表什么呢?看下源码:
/** Cache of singleton objects: bean name to bean instance. */
/** 缓存beanName和bean实例 key-->beanName,value-->beanInstance */
private final Map singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
/** 缓存beanName和beanFactory key-->beanName,value-->beanFactory */
private final Map> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
/** 缓存beanName和bean实例 key-->beanName,value-->beanInstance 该缓存主要为了解决bean的循环依赖引用 */
private final Map earlySingletonObjects = new HashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */
/** 缓存所有注册的单例beanName */
private final Set registeredSingletons = new LinkedHashSet<>(256);
以上代码片段摘取了比较重要的缓存定义:
- singletonObjects:缓存beanName和bean实例 key-->beanName,value-->beanInstance
- singletonFactories:缓存beanName和beanFactory key-->beanName,value-->beanFactory
- earlySingletonObjects:缓存beanName和bean实例 key-->beanName,value-->beanInstance
该缓存主要为了解决bean的循环依赖引用
- registeredSingletons:缓存所有注册的单例beanName
其他的对象暂时先不做介绍了,因为以上这些对象,我们将会在本小节中用到,大家先有所了解。
1.测试用例
在day01下的MyTest类中增加如下测试方法。该方法调用了两次getBean方法,第一次会创建新的Dog实例,而第二次则会从缓存中获取Dog实例。
// 从缓存中获取单例bean
@Test
public void test16() {
// 1、创建新的Dog实例
Dog dog1 = xmlBeanFactory.getBean("dog1", Dog.class);
// 2、从缓存中获取Dog实例
dog1 = xmlBeanFactory.getBean("dog1", Dog.class);
dog1.sayHello();
}
1.getBean方法简析
getBean方法是IoC容器的核心方法之一,该方法的作用是从IoC容器获取bean的实例。打开该方法并跳转至doGetBean方法。
protected T doGetBean(final String name, @Nullable final Class requiredType, @Nullable final Object[] args, boolean typeCheckOnly)
throws BeansException {
// 1、转换bean的名称,去掉&前缀,且如果bean有别名的话,优先使用别名
final String beanName = transformedBeanName(name);
Object bean;
// 2、从缓存中获取bean
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
// 3、如果未能从缓存中获取到bean,则要重新创建bean
else {
// Fail if we're already creating this bean instance: We're assumably within a circular reference.
// 判断指定的原型模式的bean是否当前正在创建(在当前线程内),如果是->则抛出异常(Spring不会解决原型模式bean的循环依赖)
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
// 检测bean definition是否存在beanFactory中
BeanFactory parentBeanFactory = getParentBeanFactory();
// 如果当前BeanFactory中不包含给定beanName的beanDefinition定义,且父beanFactory不为空,则去父beanFactory中再次查找
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 将name转换为原始beanName
// 因为这里的name已经经过beanName的规范处理,例如:&myBean-->规范-->myBean
// 所以当我们再次去父beanFactory查找时,要将beanName再次转换为原始的beanName,myBean-->回转-->&myBean
String nameToLookup = originalBeanName(name);
// 下面会递归调用各种getBean的方法重载,从当前bean的父factoryBean中加载bean
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// 参数不为空,则委托parentBeanFactory使用显式参数调动
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// 参数为空,则委托parentBeanFactory使用标准的getBean方法获取bean
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
// 否则委托parentBeanFactory使用默认的getBean方法
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
// 如果当前bean不是用于类型检查,则将该bean标记为已经被创建或者即将被创建
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
// 合并beanDefinition,如果指定的bean是一个子bean的话,则遍历其所有的父bean
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 校验合并的beanDefinition,如果验证失败,则抛出异常
checkMergedBeanDefinition(mbd, beanName, args);
// 确保初始化当前bean所依赖的bean。
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
// 循环所有的依赖bean,并递归实例化
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 注册依赖
registerDependentBean(dep, beanName);
try {
// 实例化依赖的bean
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// 创建单例bean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
// 创建bean
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);
}
// 创建原型模式bean
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
该方法的处理流程分支较多,我们先来分析从缓存中获取单例bean的过程。
2.transformedBeanName转换bean的名称分析
该方法的作用是:转换bean的名称,去掉&前缀,且如果bean有别名的话,优先使用别名
protected String transformedBeanName(String name) {
// 转换并规范beanName
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
该方法分为两步执行,转换beanName和规范beanName。
- 转换beanName
该方法的作用是返回bean的真实名称,去掉FactoryBean引用前缀&
符号
/**
* 返回bean的真实名称,去掉FactoryBean引用前缀
* Return the actual bean name, stripping out the factory dereference
* prefix (if any, also stripping repeated factory prefixes if found).
* @param name the name of the bean
* @return the transformed name
* @see BeanFactory#FACTORY_BEAN_PREFIX
*/
public static String transformedBeanName(String name) {
String beanName = name;
//beanName前缀为&,循环截取直至所有&被去掉
while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
return beanName;
}
- 规范规范beanName
/**
* 确定原始名称,将别名解析为规范名称。
* Determine the raw name, resolving aliases to canonical names.
* @param name the user-specified name 用户指定的beanName
* @return the transformed name 转换后的beanName
*/
public String canonicalName(String name) {
String canonicalName = name;
// Handle aliasing...
String resolvedName;
do {
//从别名缓存Map中获取对应beanName
resolvedName = this.aliasMap.get(canonicalName);
if (resolvedName != null) {
canonicalName = resolvedName;
}
}
while (resolvedName != null);
return canonicalName;
}
3.从缓存中获取单例bean
- getSingleton
/**
* 返回在给定名称下注册的(原始)单例对象。
* 检查已经实例化的单例,并允许对当前创建的单例的早期引用(解决循环引用)。
* Return the (raw) singleton object registered under the given name.
* Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for 要查找的bean的名称
* @param allowEarlyReference whether early references should be created or not 是否应该创建早期引用
* @return the registered singleton object, or {@code null} if none found 返回已经注册单例bean,如果未获取到则返回null
*/
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 1、从缓存中获取bean
Object singletonObject = this.singletonObjects.get(beanName);
// 2、未能获取到bean,但是允许对当前创建的单例的早期引用(解决循环引用)
// isSingletonCurrentlyInCreation-->判断指定的单例bean是否当前正在创建(Spring只解决单例bean的循环依赖问题)
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
// 从earlySingletonObjects获取提前曝光的bean
singletonObject = this.earlySingletonObjects.get(beanName);
// 未能获取到提前曝光的bean且当前的bean允许被创建早期依赖
if (singletonObject == null && allowEarlyReference) {
// 从缓存中获取BeanFactory
ObjectFactory> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 通过getObject()方法获取bean,注意:通过此方法获取的bean不是被缓存的
singletonObject = singletonFactory.getObject();
// 将获取到的singletonObject缓存至earlySingletonObjects
this.earlySingletonObjects.put(beanName, singletonObject);
// 从singletonFactories移除bean
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
该过程中包含了对bean循环依赖的处理,但是无需理会该点,我们会在接下来的章节中详细介绍循环以来的处理。
前面已经介绍过singletonObjects对象缓存beanName和bean实例 key-->beanName,value-->beanInstance
,测试用例中调用了两次getBean方法,当第二次调用时我们可以看到singletonObjects已经缓存了Dog的实例。那么该方法也就能够返回Dog的实例。
- getObjectForBeanInstance
无论是从缓存获取单例bean还是新创建的单例bean,在bean实例化之后都会调用getObjectForBeanInstance方法,该方法的作用就是判断到底是应该返回一个普通的bean的实例还是返回FactoryBean的实例。
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// 1、判断bean是否factoryBean
// Don't let calling code try to dereference the factory if the bean isn't a factory.
if (BeanFactoryUtils.isFactoryDereference(name)) {
// 当前bean是factoryBean,且beanInstance是NullBean的实例,则返回beanInstance
if (beanInstance instanceof NullBean) {
return beanInstance;
}
// 当前bean是factoryBean,但是不是FactoryBean的实例,则抛出异常
// 因BeanFactoryUtils.isFactoryDereference(name)-->只是从bean名称上进行了判断,我们通过getBean("&myBean")可以人为将一个非factoryBean当做factoryBean
// 所以这里必须要判断beanInstance是否为FactoryBean的实例
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
}
// 现在我们有了bean实例,它可能是一个普通的bean,也可能是一个FactoryBean。
// 如果它是FactoryBean,我们使用它创建一个bean实例,除非调用者实际上需要工厂的引用。
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
/**
* 下面这句话稍微有些绕,首先判断beanInstance是FactoryBean的实例,然后又加了一个非的条件,将判断结果反置
* 再加一个或条件,判断该bean的name是否有&引用,这样一来就可以判断是返回bean的实例还是返回FactoryBean对象
* 例1:我们通过getBean("&myBean"),假设myBean实现了BeanFactory接口,那么myBean肯定是FactoryBean的实例
* 此时将第一个判断条件置否,再去判断bean的name是否包含了&符,如果是的话,那么就返回FactoryBean对象本身
*
* 例2:我们通过getBean("myBean"),假设myBean是一个普通的bean,那么它肯定不是FactoryBean的实例,
* 那么该bean跟FactoryBean无任何关系,直接返回其实例即可
*
*/
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
// 如果beanDefinition为null,则尝试从缓存中获取给定的FactoryBean公开的对象
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
// 未能从缓存中获得FactoryBean公开的对象,则说明该bean是一个新创建的bean
if (object == null) {
// Return bean instance from factory.
FactoryBean> factory = (FactoryBean>) beanInstance;
// rootBeanDefinition为null,但是在beanDefinitionMap中缓存了对应的beanName
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
//合并beanDefinition(包括父类bean)
mbd = getMergedLocalBeanDefinition(beanName);
}
// 如果beanDefinition不为null,则要判断该beanDefinition对象是否通过合成获得,
// 如果不是,则说明该beanDefinition不由有程序本身定义的
boolean synthetic = (mbd != null && mbd.isSynthetic());
// 从给定的FactoryBean中获取指定的beanName对象
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
从代码中可以看到当执行到
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
便可以确定当前获取的是普通的bean实例,关于获取FactoryBean的过程,我们留在以后分析。
至此,已经从缓存中获取到了单例bean的实例。