上一篇分析了BeanFactory体系的2个类,SimpleAliasRegistry和DefaultSingletonBeanRegistry—— Spring源码分析——BeanFactory体系之抽象类、类分析(一),今天继续分析。
一、工厂Bean注册支持——FactoryBeanRegistrySupport
废话不多说,直接看我注释的源码:
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.support; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBeanNotInitializedException; /** * Support base class for singleton registries which need to handle * {@link org.springframework.beans.factory.FactoryBean} instances, * integrated with {@link DefaultSingletonBeanRegistry}'s singleton management. * * <p>Serves as base class for {@link AbstractBeanFactory}. * * @author Juergen Hoeller * @since 2.5.1 */ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry { /** 工厂Bean生产的单例的集合: FactoryBean name --> object */ private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<String, Object>(16); //返回指定FactoryBean的类型 protected Class getTypeForFactoryBean(final FactoryBean factoryBean) { try { if (System.getSecurityManager() != null) {//如果当前系统存在安全管理器 return AccessController.doPrivileged(new PrivilegedAction<Class>() {//那么返回factoryBean的类型这个操作不做权限检查,直接调用 public Class run() { return factoryBean.getObjectType(); } }, getAccessControlContext()); } else {//不存在安全管理器,就直接调用! return factoryBean.getObjectType(); } } catch (Throwable ex) { logger.warn("FactoryBean threw exception from getObjectType, despite the contract saying " + "that it should return null if the type of its object cannot be determined yet", ex); return null; } } //根据FactoryBean名,返回其生产的Object,从缓存中取 protected Object getCachedObjectForFactoryBean(String beanName) { Object object = this.factoryBeanObjectCache.get(beanName); return (object != NULL_OBJECT ? object : null); } //从工厂Bean中取实例,实际调用下面的doGetObjectFromFactoryBean方法。 protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName, boolean shouldPostProcess) { if (factory.isSingleton() && containsSingleton(beanName)) {//若工厂是单例,且本容器包含beanName对应的单例类 synchronized (getSingletonMutex()) {//以所有的单例集合为锁 Object object = this.factoryBeanObjectCache.get(beanName);//根据beanName从factoryBeanObjectCache中取 if (object == null) {//若取不到 object = doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));//放进factoryBeanObjectCache } return (object != NULL_OBJECT ? object : null); } } else {//否则,直接 return doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); } } //从工厂Bean中取实例 private Object doGetObjectFromFactoryBean( final FactoryBean factory, final String beanName, final boolean shouldPostProcess) throws BeanCreationException { Object object; //跟getTypeForFactoryBean的实现一样。 try { if (System.getSecurityManager() != null) {//若系统存在安全管理器 AccessControlContext acc = getAccessControlContext();//得到当前容器的安全访问上下文 try {//返回factoryBean的类型这个操作不做权限检查,直接调用 object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return factory.getObject(); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else {//否则直接取 object = factory.getObject(); } } catch (FactoryBeanNotInitializedException ex) { throw new BeanCurrentlyInCreationException(beanName, ex.toString()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } //如果从beanFactory取不到,且这个实例即将被创建,抛出异常 if (object == null && isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } //若取不到,且这个实例允许前处理 if (object != null && shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName);//这里简单返回,前处理的功能留给子类重写 } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex); } } return object; } //这里简单返回Object,留给子类重写 protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException { return object; } //如果这个Object是FactoryBean类型,就转换成FactoryBean返回 protected FactoryBean getFactoryBean(String beanName, Object beanInstance) throws BeansException { if (!(beanInstance instanceof FactoryBean)) { throw new BeanCreationException(beanName, "Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean"); } return (FactoryBean) beanInstance; } //移除单例类这个方法重写,父类的移除之外,还要移除factoryBeanObjectCache中的。 @Override protected void removeSingleton(String beanName) { super.removeSingleton(beanName); this.factoryBeanObjectCache.remove(beanName); } //返回当前容器的安全访问上下文 protected AccessControlContext getAccessControlContext() { return AccessController.getContext(); } }
具体:
1、1个不可变的实例属性ConcurrentHashMap来存放工厂Bean生产的单例的集合:FactoryBean name --> object。
2、1个方法返回指定FactoryBean的类型的方法。
3、1个根据FactoryBean名,返回其生产的Object的方法。
4、2个从工厂Bean中取实例的方法。实际是一个方法调用另一个,取不到则返回空。
5、1个postProcessObjectFromFactoryBean的方法,留给子类重写。
6、1个取工厂Bean的方法——如果这个Object是FactoryBean类型,就转换成FactoryBean返回
7、1个重写父类的removeSingleton方法,移除单例的时候,父类的移除之外,还要移除factoryBeanObjectCache中的。
8、1个返回当前容器的安全访问上下文的方法。
总结:
这个类FactoryBeanRegistrySupport,类如其名,实现了对工厂Bean注册的支持。值得注意的是,这个类有较多类似如下的写法:
if (System.getSecurityManager() != null) {//如果当前系统存在安全管理器 return AccessController.doPrivileged(new PrivilegedAction<Class>() { public Class run() { //实际处理 } }, getAccessControlContext()); } else {//不存在安全管理器,就直接调用! //实际处理 }
这个方法的意思是,如果当前系统存在安全管理器,那么接下来的操作不做权限检查,直接调用。而如果不存在,OK,那当然是直接调用了。这是JDK层面的一个系统安全管理工具,某些情况下,可以避免系统进行安全检查。这里稍作了解即可。在学习JVM的时候可仔细了解原理。
除此之外,这里可以了解一下这个类比较重要的方法doGetObjectFromFactoryBean,是从工厂Bean中取实例的方法,源码已经给出,这里重点指出一下,不必折叠了:
//从工厂Bean中取实例,shouldPostProcess指的是是否允许提前处理 private Object doGetObjectFromFactoryBean( final FactoryBean factory, final String beanName, final boolean shouldPostProcess) throws BeanCreationException { Object object; //跟getTypeForFactoryBean的实现一样。 try { if (System.getSecurityManager() != null) {//若系统存在安全管理器 AccessControlContext acc = getAccessControlContext();//得到当前容器的安全访问上下文 try {//返回factoryBean的类型这个操作不做权限检查,直接调用 object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return factory.getObject(); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else {//否则直接取 object = factory.getObject(); } } catch (FactoryBeanNotInitializedException ex) { throw new BeanCurrentlyInCreationException(beanName, ex.toString()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } //如果从beanFactory取不到,且这个实例即将被创建,抛出异常 if (object == null && isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } //若取不到,并非即将创建、且这个实例允许前处理 if (object != null && shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName);//这里简单返回,前处理的功能留给子类重写 } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex); } } return object; }
相信上面已经解释的很清楚了。
二、最重要的抽象类——AbstractBeanFactory
(PS:这个类的方法实在是多的骇人,看得我实在是头都大了。不多看到后面,发现很多方法其实也就是那么回事。源码注释了大部分,且看看咯!)
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory { //父工厂的引用 private BeanFactory parentBeanFactory; //类加载器 private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); //临时类加载器 private ClassLoader tempClassLoader; /** Whether to cache bean metadata or rather reobtain it for every access */ private boolean cacheBeanMetadata = true; //Bean表达式分解器,用来分解Bean定义中的表达式 private BeanExpressionResolver beanExpressionResolver; //转换服务,用来替代属性编辑器的 private ConversionService conversionService; //属性编辑登记员集合,容量为4的LinkedHashSet private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<PropertyEditorRegistrar>(4); //通用的类型转换器,重写了默认的属相编辑器机制 private TypeConverter typeConverter; //默认的属性编辑器集合 private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<Class<?>, Class<? extends PropertyEditor>>(4); //嵌入值转换器集合 private final List<StringValueResolver> embeddedValueResolvers = new LinkedList<StringValueResolver>(); //BeanPostProcessor处理器集合 private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>(); //标记是否有InstantiationAwareBeanPostProcessors实例被注册 private boolean hasInstantiationAwareBeanPostProcessors; //标记是否有DestructionAwareBeanPostProcessors实例被注册 private boolean hasDestructionAwareBeanPostProcessors; //范围标识符和Scope实例的对应的Map private final Map<String, Scope> scopes = new HashMap<String, Scope>(8); //安全上下文Provider,可以得到安全管理器的安全上下文 private SecurityContextProvider securityContextProvider; //合并后的Bean根定义的集合 private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<String, RootBeanDefinition>(64); //至少被创建过一次的Bean的集合 private final Map<String, Boolean> alreadyCreated = new ConcurrentHashMap<String, Boolean>(64); //当前正在创建的原型,当前线程相关 private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal<Object>("Prototype beans currently in creation"); //空构造方法 public AbstractBeanFactory() { } //指定父Bean工厂的构造方法 public AbstractBeanFactory(BeanFactory parentBeanFactory) { this.parentBeanFactory = parentBeanFactory; } //--------------------------------------------------------------------- // 3个getBean,BeanFactory接口的实现方法,实质是在调用doGetBean //--------------------------------------------------------------------- public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return doGetBean(name, requiredType, null, false); } public Object getBean(String name, Object... args) throws BeansException { return doGetBean(name, null, args, false); } // 提供创建时需要参数列表的getBean public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException { return doGetBean(name, requiredType, args, false); } //从容器中获取bean的基本方法。 @SuppressWarnings("unchecked") protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name);//在aliasMap中取得的标准名 Object bean; // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName);//首先在单例集合中取 if (sharedInstance != null && args == null) {//如果取得到,没有指定参数 if (logger.isDebugEnabled()) {//若Log允许调试 if (isSingletonCurrentlyInCreation(beanName)) {//若正准备创建,输出日志 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } ////根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { if (isPrototypeCurrentlyInCreation(beanName)) {//如果正在被创建,就抛出异常 throw new BeanCurrentlyInCreationException(beanName); } BeanFactory parentBeanFactory = getParentBeanFactory();//取本容器的父容器 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {//若存在父容器,且本容器不存在对应的Bean定义 String nameToLookup = originalBeanName(name);//取原始的Bean名 if (args != null) {//若参数列表存在 // 那么用父容器根据原始Bean名和参数列表返回 return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // 参数列表不要求,那就直接根据原始名称和要求的类型返回 return parentBeanFactory.getBean(nameToLookup, requiredType); } } //如果不需要类型检查,标记其已经被创建 if (!typeCheckOnly) { markBeanAsCreated(beanName); } //根据beanName取其根Bean定义 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); String[] dependsOn = mbd.getDependsOn();//得到这个根定义的所有依赖 if (dependsOn != null) { for (String dependsOnBean : dependsOn) { getBean(dependsOnBean);//注册这个Bean //注册一个Bean和依赖于它的Bean(后参数依赖前参数) registerDependentBean(dependsOnBean, beanName); } } // 如果Bean定义是单例,就在返回单例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } } }); //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //如果是原型 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 '" + scopeName + "'"); } try {//根据范围创建实例 Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args);//原型创建前,与当前线程绑定 } finally { ////原型创建后,与当前线程解除绑定 afterPrototypeCreation(beanName); } } }); //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 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); } } } //判断要求的类型是否和Bean实例的类型正在匹配 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { try { return getTypeConverter().convertIfNecessary(bean, requiredType);//转换类型,不抛出异常就说明类型匹配 } 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 public boolean containsBean(String name) { String beanName = transformedBeanName(name); // (如果是否包含单例 或 包含Bean定义)且 (为工厂Bean的产物 或 本身就是工厂bean),就返回true if (containsSingleton(beanName) || containsBeanDefinition(beanName)) { return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name)); } // 如果不包含单例且不包含Bean定义,就从父类去查找 BeanFactory parentBeanFactory = getParentBeanFactory(); return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name))); } //判断指定Bean是否为单例 public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Object beanInstance = getSingleton(beanName, false);//首先从单例集合中取 if (beanInstance != null) {//取不到,就判断它是不是FactoryBean的实例 if (beanInstance instanceof FactoryBean) { // 如果是,要求它是工厂Bean产生的实例或这个工厂bean是单例 return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean<?>) beanInstance).isSingleton()); } else {// 如果不是,要求它不是工厂Bean产生的实例 return !BeanFactoryUtils.isFactoryDereference(name); } }//若虽然取不到,但是单例集合中包含它的名字,说明它是单例 else if (containsSingleton(beanName)) { return true; } else { //从父工厂中去查询Bean定义 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //父工厂找不到Bean定义,那就在父工厂根据原始名去查是否为单例 return parentBeanFactory.isSingleton(originalBeanName(name)); } //返回一个合并后的根Bean定义 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // In case of FactoryBean, return singleton status of created object if not a dereference. //若该根定义是单例 if (mbd.isSingleton()) { if (isFactoryBean(beanName, mbd)) { //若该根定义为工厂Bean if (BeanFactoryUtils.isFactoryDereference(name)) {//判断是否为工厂产生的实例 return true; } //取对应的工厂,判断该工厂Bean是否为单例 FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); return factoryBean.isSingleton(); } else { // 是否不为工厂Bean产生的实例(此时,即,该根定义不为工厂Bean,且不为工厂Bean产生的实例的时候,由于根定义是单例,那么它就是单例) return !BeanFactoryUtils.isFactoryDereference(name); } } else { return false; } } } //判断是否为原型 public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); BeanFactory parentBeanFactory = getParentBeanFactory();//得到父工厂 //若父工厂中的定义为原型,就为原型 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { return parentBeanFactory.isPrototype(originalBeanName(name)); } //若合并后的根定义为原型,且不是工厂Bean产生的实例、或本身是工厂Bean,那么就为原型 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (mbd.isPrototype()) { return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd)); } else { if (BeanFactoryUtils.isFactoryDereference(name)) {//若为工厂Bean产生的实例 return false; } if (isFactoryBean(beanName, mbd)) {//若为工厂Bean,取它产生的Bean,判断SmartFactoryBean final FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factoryBean).isPrototype()) || !factoryBean.isSingleton()); } }, getAccessControlContext()); } else { return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factoryBean).isPrototype()) || !factoryBean.isSingleton()); } } else { return false; } } } //判断类型是否匹配 public boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Class<?> typeToMatch = (targetType != null ? targetType : Object.class); Object beanInstance = getSingleton(beanName, false);//取name对应的单例 if (beanInstance != null) { if (beanInstance instanceof FactoryBean) {//若为工厂Bean //若不是工厂Bean产生的实例 if (!BeanFactoryUtils.isFactoryDereference(name)) { //取工厂Bean的类型与targetType进行对比 Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance); return (type != null && ClassUtils.isAssignable(typeToMatch, type)); } else { return ClassUtils.isAssignableValue(typeToMatch, beanInstance); } } //不是工厂Bean,那就直接判断 else { return !BeanFactoryUtils.isFactoryDereference(name) && ClassUtils.isAssignableValue(typeToMatch, beanInstance); } } //单例表中,对应的Key没有值,也不包含Bean定义,说明没有注册,返回false else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { return false; } //以下是包含Bean定义的情况 else { //先查父类的Bean定义 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType); } //直接查合并后的根定义 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //构建类型数组 Class[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ? new Class[] {typeToMatch} : new Class[] {FactoryBean.class, typeToMatch}); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. //得到Bean定义的持有者 BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {//若为Bean工厂生成的实例,先得到根定义 RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);//得到预测的根定义 if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return typeToMatch.isAssignableFrom(targetClass); } } Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);//预测后的类型 if (beanType == null) { return false; } if (FactoryBean.class.isAssignableFrom(beanType)) {//BeanFactory是否为其子类 if (!BeanFactoryUtils.isFactoryDereference(name)) {//若不为工厂Bean的产物 // If it's a FactoryBean, we want to look at what it creates, not the factory class. beanType = getTypeForFactoryBean(beanName, mbd); if (beanType == null) { return false; } } } else if (BeanFactoryUtils.isFactoryDereference(name)) {//若为工厂类Bean的产物 beanType = predictBeanType(beanName, mbd, FactoryBean.class);//预测类型 if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) { return false; } } return typeToMatch.isAssignableFrom(beanType); } } //返回类型 public Class<?> getType(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { return getTypeForFactoryBean((FactoryBean<?>) beanInstance); } else { return beanInstance.getClass(); } } else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { // null instance registered return null; } else { // No singleton instance found -> check bean definition. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.getType(originalBeanName(name)); } RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return targetClass; } } Class<?> beanClass = predictBeanType(beanName, mbd); // Check bean class whether we're dealing with a FactoryBean. if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. return getTypeForFactoryBean(beanName, mbd); } else { return beanClass; } } else { return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null); } } } //重写了,得到别名的方法。 @Override public String[] getAliases(String name) { String beanName = transformedBeanName(name); List<String> aliases = new ArrayList<String>(); boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX); String fullBeanName = beanName; if (factoryPrefix) { fullBeanName = FACTORY_BEAN_PREFIX + beanName; } if (!fullBeanName.equals(name)) { aliases.add(fullBeanName); } String[] retrievedAliases = super.getAliases(beanName); for (String retrievedAlias : retrievedAliases) { String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAlias; if (!alias.equals(name)) { aliases.add(alias); } } if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) { BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null) { aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName))); } } return StringUtils.toStringArray(aliases); } //--------------------------------------------------------------------- // Implementation of HierarchicalBeanFactory interface //--------------------------------------------------------------------- //返回本Bean工厂的父Bean工厂 public BeanFactory getParentBeanFactory() { return this.parentBeanFactory; } //是否在本容器中(就是说,并不是工厂bean生产出来的) public boolean containsLocalBean(String name) { String beanName = transformedBeanName(name); // 转换后的名字 //(是否为单例或有对应的Bean定义) 且(不是工厂Bean生产出来的 或 本身就是工厂bean) return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) && (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName))); } //--------------------------------------------------------------------- // Implementation of ConfigurableBeanFactory interface //--------------------------------------------------------------------- public void setParentBeanFactory(BeanFactory parentBeanFactory) { if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) { throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory); } this.parentBeanFactory = parentBeanFactory; } public void setBeanClassLoader(ClassLoader beanClassLoader) { this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader()); } public ClassLoader getBeanClassLoader() { return this.beanClassLoader; } public void setTempClassLoader(ClassLoader tempClassLoader) { this.tempClassLoader = tempClassLoader; } public ClassLoader getTempClassLoader() { return this.tempClassLoader; } public void setCacheBeanMetadata(boolean cacheBeanMetadata) { this.cacheBeanMetadata = cacheBeanMetadata; } public boolean isCacheBeanMetadata() { return this.cacheBeanMetadata; } public void setBeanExpressionResolver(BeanExpressionResolver resolver) { this.beanExpressionResolver = resolver; } public BeanExpressionResolver getBeanExpressionResolver() { return this.beanExpressionResolver; } public void setConversionService(ConversionService conversionService) { this.conversionService = conversionService; } public ConversionService getConversionService() { return this.conversionService; } public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) { Assert.notNull(registrar, "PropertyEditorRegistrar must not be null"); this.propertyEditorRegistrars.add(registrar); } /** * Return the set of PropertyEditorRegistrars. */ public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) { Assert.notNull(requiredType, "Required type must not be null"); Assert.isAssignable(PropertyEditor.class, propertyEditorClass); this.customEditors.put(requiredType, propertyEditorClass); } public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) { registerCustomEditors(registry); } /** * Return the map of custom editors, with Classes as keys and PropertyEditor classes as values. */ public Map<Class<?>, Class<? extends PropertyEditor>> getCustomEditors() { return this.customEditors; } public void setTypeConverter(TypeConverter typeConverter) { this.typeConverter = typeConverter; } //得到通用的类型转换器 protected TypeConverter getCustomTypeConverter() { return this.typeConverter; } //得到类型转换器 public TypeConverter getTypeConverter() { TypeConverter customConverter = getCustomTypeConverter(); if (customConverter != null) { return customConverter; } else {//若本容器未注册类型转换器,就创建一个简单的类型转换器 SimpleTypeConverter typeConverter = new SimpleTypeConverter(); typeConverter.setConversionService(getConversionService()); registerCustomEditors(typeConverter); return typeConverter; } } public void addEmbeddedValueResolver(StringValueResolver valueResolver) { Assert.notNull(valueResolver, "StringValueResolver must not be null"); this.embeddedValueResolvers.add(valueResolver); } public String resolveEmbeddedValue(String value) { String result = value; for (StringValueResolver resolver : this.embeddedValueResolvers) { if (result == null) { return null; } result = resolver.resolveStringValue(result); } return result; } public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) { Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null"); this.beanPostProcessors.remove(beanPostProcessor); this.beanPostProcessors.add(beanPostProcessor); if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) { this.hasInstantiationAwareBeanPostProcessors = true; } if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) { this.hasDestructionAwareBeanPostProcessors = true; } } public int getBeanPostProcessorCount() { return this.beanPostProcessors.size(); } /** * Return the list of BeanPostProcessors that will get applied * to beans created with this factory. */ public List<BeanPostProcessor> getBeanPostProcessors() { return this.beanPostProcessors; } /** * Return whether this factory holds a InstantiationAwareBeanPostProcessor * that will get applied to singleton beans on shutdown. * @see #addBeanPostProcessor * @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor */ protected boolean hasInstantiationAwareBeanPostProcessors() { return this.hasInstantiationAwareBeanPostProcessors; } /** * Return whether this factory holds a DestructionAwareBeanPostProcessor * that will get applied to singleton beans on shutdown. * @see #addBeanPostProcessor * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor */ protected boolean hasDestructionAwareBeanPostProcessors() { return this.hasDestructionAwareBeanPostProcessors; } public void registerScope(String scopeName, Scope scope) { Assert.notNull(scopeName, "Scope identifier must not be null"); Assert.notNull(scope, "Scope must not be null"); if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) { throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'"); } this.scopes.put(scopeName, scope); } public String[] getRegisteredScopeNames() { return StringUtils.toStringArray(this.scopes.keySet()); } public Scope getRegisteredScope(String scopeName) { Assert.notNull(scopeName, "Scope identifier must not be null"); return this.scopes.get(scopeName); } /** * Set the security context provider for this bean factory. If a security manager * is set, interaction with the user code will be executed using the privileged * of the provided security context. */ public void setSecurityContextProvider(SecurityContextProvider securityProvider) { this.securityContextProvider = securityProvider; } /** * Delegate the creation of the access control context to the * {@link #setSecurityContextProvider SecurityContextProvider}. */ @Override public AccessControlContext getAccessControlContext() { return (this.securityContextProvider != null ? this.securityContextProvider.getAccessControlContext() : AccessController.getContext()); } public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { Assert.notNull(otherFactory, "BeanFactory must not be null"); setBeanClassLoader(otherFactory.getBeanClassLoader()); setCacheBeanMetadata(otherFactory.isCacheBeanMetadata()); setBeanExpressionResolver(otherFactory.getBeanExpressionResolver()); if (otherFactory instanceof AbstractBeanFactory) { AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory; this.customEditors.putAll(otherAbstractFactory.customEditors); this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars); this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors); this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors || otherAbstractFactory.hasInstantiationAwareBeanPostProcessors; this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors || otherAbstractFactory.hasDestructionAwareBeanPostProcessors; this.scopes.putAll(otherAbstractFactory.scopes); this.securityContextProvider = otherAbstractFactory.securityContextProvider; } else { setTypeConverter(otherFactory.getTypeConverter()); } } //返回合并后的bean定义(父Bean定义和子Bean定义合并) public BeanDefinition getMergedBeanDefinition(String name) throws BeansException { String beanName = transformedBeanName(name); // Efficiently check whether bean definition exists in this factory. //若Bean定义不存在,且本容器父工厂为ConfigurableBeanFactory的实例,让父工厂来调用这个方法 if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName); } //否则直接从本地合并后的Bean定义中取 return getMergedLocalBeanDefinition(beanName); } public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { return (beanInstance instanceof FactoryBean); } else if (containsSingleton(beanName)) { // null instance registered return false; } // No singleton instance found -> check bean definition. if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name); } return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName)); } @Override public boolean isActuallyInCreation(String beanName) { return isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName); } // 判断指定的原型是否正在被创建 protected boolean isPrototypeCurrentlyInCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); return (curVal != null && (curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName)))); } //原型创建前回调,需要子类重写 @SuppressWarnings("unchecked") protected void beforePrototypeCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); if (curVal == null) {//原型创建状态与当前线程绑定 this.prototypesCurrentlyInCreation.set(beanName); } else if (curVal instanceof String) { Set<String> beanNameSet = new HashSet<String>(2); beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } //这里多余了。。。 else { Set<String> beanNameSet = (Set<String>) curVal; beanNameSet.add(beanName); } } //创建原型后,从当前线程解除绑定 @SuppressWarnings("unchecked") protected void afterPrototypeCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); if (curVal instanceof String) { this.prototypesCurrentlyInCreation.remove(); } else if (curVal instanceof Set) { Set<String> beanNameSet = (Set<String>) curVal; beanNameSet.remove(beanName); if (beanNameSet.isEmpty()) { this.prototypesCurrentlyInCreation.remove(); } } } public void destroyBean(String beanName, Object beanInstance) { destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName)); } /** * Destroy the given bean instance (usually a prototype instance * obtained from this factory) according to the given bean definition. * @param beanName the name of the bean definition * @param beanInstance the bean instance to destroy * @param mbd the merged bean definition */ protected void destroyBean(String beanName, Object beanInstance, RootBeanDefinition mbd) { new DisposableBeanAdapter(beanInstance, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy(); } public void destroyScopedBean(String beanName) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (mbd.isSingleton() || mbd.isPrototype()) { throw new IllegalArgumentException( "Bean name '" + beanName + "' does not correspond to an object in a mutable scope"); } String scopeName = mbd.getScope(); Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope SPI registered for scope '" + scopeName + "'"); } Object bean = scope.remove(beanName); if (bean != null) { destroyBean(beanName, bean, mbd); } } //--------------------------------------------------------------------- // Implementation methods //--------------------------------------------------------------------- //变换后的Bean名称(先去掉BeanFactory前缀,然后在aliasMap中取标准名) protected String transformedBeanName(String name) { return canonicalName(BeanFactoryUtils.transformedBeanName(name)); } //返回原始的Bean名 protected String originalBeanName(String name) { String beanName = transformedBeanName(name); if (name.startsWith(FACTORY_BEAN_PREFIX)) { beanName = FACTORY_BEAN_PREFIX + beanName; } return beanName; } /** * Initialize the given BeanWrapper with the custom editors registered * with this factory. To be called for BeanWrappers that will create * and populate bean instances. * <p>The default implementation delegates to {@link #registerCustomEditors}. * Can be overridden in subclasses. * @param bw the BeanWrapper to initialize */ protected void initBeanWrapper(BeanWrapper bw) { bw.setConversionService(getConversionService()); registerCustomEditors(bw); } /** * Initialize the given PropertyEditorRegistry with the custom editors * that have been registered with this BeanFactory. * <p>To be called for BeanWrappers that will create and populate bean * instances, and for SimpleTypeConverter used for constructor argument * and factory method type conversion. * @param registry the PropertyEditorRegistry to initialize */ protected void registerCustomEditors(PropertyEditorRegistry registry) { PropertyEditorRegistrySupport registrySupport = (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null); if (registrySupport != null) { registrySupport.useConfigValueEditors(); } if (!this.propertyEditorRegistrars.isEmpty()) { for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) { try { registrar.registerCustomEditors(registry); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { BeanCreationException bce = (BeanCreationException) rootCause; if (isCurrentlyInCreation(bce.getBeanName())) { if (logger.isDebugEnabled()) { logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() + "] failed because it tried to obtain currently created bean '" + ex.getBeanName() + "': " + ex.getMessage()); } onSuppressedException(ex); continue; } } throw ex; } } } if (!this.customEditors.isEmpty()) { for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) { Class<?> requiredType = entry.getKey(); Class<? extends PropertyEditor> editorClass = entry.getValue(); registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)); } } } //返回一个合并后的根Bean定义(父Bean定义和子Bean定义合并)(从当前容器取) protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);//首先直接从合并根定义集合中取 if (mbd != null) { return mbd; } //根据bean名和其对应的Bean定义,取其根Bean根定义 return getMergedBeanDefinition(beanName, getBeanDefinition(beanName)); } //根据Bean名和Bean定义取其Bean根定义 protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd) throws BeanDefinitionStoreException { return getMergedBeanDefinition(beanName, bd, null);//调用重载方法 } //根据Bean名称返回根定义(若给定的Bean定义为子Bean定义,那么合并它的父Bean定义) protected RootBeanDefinition getMergedBeanDefinition( String beanName, BeanDefinition bd, BeanDefinition containingBd) throws BeanDefinitionStoreException { synchronized (this.mergedBeanDefinitions) { RootBeanDefinition mbd = null; //若给定的Bean定义并没有包含子Bean定义,那么直接根据Bean名取根定义 if (containingBd == null) { mbd = this.mergedBeanDefinitions.get(beanName); } if (mbd == null) {//若取不到 if (bd.getParentName() == null) {//若Bean定义没有父类,就很简单了 if (bd instanceof RootBeanDefinition) {//若Bean定义是RootBeanDefinition的实例,克隆、强转后返回 mbd = ((RootBeanDefinition) bd).cloneBeanDefinition(); } else {//否则,根据Bean定义,来构造一个根Bean定义 mbd = new RootBeanDefinition(bd); } } else {//若Bean定义有父类 // Child bean definition: needs to be merged with parent. BeanDefinition pbd; try { String parentBeanName = transformedBeanName(bd.getParentName());//取其父Bean定义的名字 if (!beanName.equals(parentBeanName)) {//若Bean名字并不是bd的父Bean的名字 pbd = getMergedBeanDefinition(parentBeanName);//根据父Bean定义名称来返回合并后的bean定义 } else {//如果beanName对应的Bean就是bd的父Bean if (getParentBeanFactory() instanceof ConfigurableBeanFactory) {//若父Bean工厂为ConfigurableBeanFactory的实例 // 那么强转成ConfigurableBeanFactory后再调用合并方法 pbd = ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(parentBeanName); } else {//若父Bean工厂不是ConfigurableBeanFactory的实例,就抛出异常 throw new NoSuchBeanDefinitionException(bd.getParentName(), "Parent name '" + bd.getParentName() + "' is equal to bean name '" + beanName + "': cannot be resolved without an AbstractBeanFactory parent"); } } } catch (NoSuchBeanDefinitionException ex) { throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex); } // 深度复制 mbd = new RootBeanDefinition(pbd);//根据Bean定义生成一个根Bean定义 mbd.overrideFrom(bd);//将Bean定义的属性复制进自己的定义(根Bean定义)中 } if (!StringUtils.hasLength(mbd.getScope())) {//如果根Bean定义未设置范围 mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);//那么设置其范围为单例 } // 若本根Bean定义包含Bean定义、本根Bean定义为单例且包含的Bean定义并不是单例 if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) { mbd.setScope(containingBd.getScope());// 那么将本根Bean定义的范围设置为包含的Bean定义的范围 } //若本根Bean定义不包含Bean定义,且是缓存Bean元数据(重写前均为true)且Bean定义是否有资格缓存(默认实现是,这个Bean已经创建便有资格) if (containingBd == null && isCacheBeanMetadata() && isBeanEligibleForMetadataCaching(beanName)) { this.mergedBeanDefinitions.put(beanName, mbd);//放进mergedBeanDefinitions中 } } return mbd; } } //检查Bean定义,抛出异常 protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args) throws BeanDefinitionStoreException { if (mbd.isAbstract()) { throw new BeanIsAbstractException(beanName); } if (args != null && !mbd.isPrototype()) { throw new BeanDefinitionStoreException( "Can only specify arguments for the getBean method when referring to a prototype bean definition"); } } /** * Remove the merged bean definition for the specified bean, * recreating it on next access. * @param beanName the bean name to clear the merged definition for */ protected void clearMergedBeanDefinition(String beanName) { this.mergedBeanDefinitions.remove(beanName); } //解析类型,处理异常 protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch) throws CannotLoadBeanClassException { try { if (mbd.hasBeanClass()) { return mbd.getBeanClass(); } if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { public Class<?> run() throws Exception { return doResolveBeanClass(mbd, typesToMatch); } }, getAccessControlContext()); } else { return doResolveBeanClass(mbd, typesToMatch); } } catch (PrivilegedActionException pae) { ClassNotFoundException ex = (ClassNotFoundException) pae.getException(); throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); } catch (ClassNotFoundException ex) { throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); } catch (LinkageError err) { throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err); } } // 真正的解析类型 private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch) throws ClassNotFoundException { if (!ObjectUtils.isEmpty(typesToMatch)) { ClassLoader tempClassLoader = getTempClassLoader();//找到临时的类加载器 if (tempClassLoader != null) { if (tempClassLoader instanceof DecoratingClassLoader) {//若为装饰类加载器 DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader; for (Class<?> typeToMatch : typesToMatch) { dcl.excludeClass(typeToMatch.getName()); } } String className = mbd.getBeanClassName(); return (className != null ? ClassUtils.forName(className, tempClassLoader) : null); } } return mbd.resolveBeanClass(getBeanClassLoader()); } /** * Evaluate the given String as contained in a bean definition, * potentially resolving it as an expression. * @param value the value to check * @param beanDefinition the bean definition that the value comes from * @return the resolved value * @see #setBeanExpressionResolver */ protected Object evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) { if (this.beanExpressionResolver == null) { return value; } Scope scope = (beanDefinition != null ? getRegisteredScope(beanDefinition.getScope()) : null); return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope)); } //预测类型 protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { //若根Bena定义的工厂方法名存在,说明它是工厂Bean创建的,无法预测类型? if (mbd.getFactoryMethodName() != null) { return null; } //否则,解析Bean的Class return resolveBeanClass(mbd, beanName, typesToMatch); } /** * Check whether the given bean is defined as a {@link FactoryBean}. * @param beanName the name of the bean * @param mbd the corresponding bean definition */ protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class); return (beanType != null && FactoryBean.class.isAssignableFrom(beanType)); } //返回工厂Bean的类型 protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) { if (!mbd.isSingleton()) { return null; } try { FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true); return getTypeForFactoryBean(factoryBean); } catch (BeanCreationException ex) { // Can only happen when getting a FactoryBean. if (logger.isDebugEnabled()) { logger.debug("Ignoring bean creation exception on FactoryBean type check: " + ex); } onSuppressedException(ex); return null; } } //标记这个Bean已经被创建 protected void markBeanAsCreated(String beanName) { this.alreadyCreated.put(beanName, Boolean.TRUE); } /** * Determine whether the specified bean is eligible for having * its bean definition metadata cached. * @param beanName the name of the bean * @return {@code true} if the bean's metadata may be cached * at this point already */ //若本根Bean定义包含Bean元定义作为缓存,这个方法应被之类覆盖,这里仅判断Bean是否已经被创建 protected boolean isBeanEligibleForMetadataCaching(String beanName) { return this.alreadyCreated.containsKey(beanName); } /** * Remove the singleton instance (if any) for the given bean name, * but only if it hasn't been used for other purposes than type checking. * @param beanName the name of the bean * @return {@code true} if actually removed, {@code false} otherwise */ protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) { if (!this.alreadyCreated.containsKey(beanName)) { removeSingleton(beanName); return true; } else { return false; } } //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { //如果这个Bean是工厂Bean创建的 且 这个Bean实例并不是FactoryBean实例,抛异常 if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); } //如果这个Bean实例并不是FactoryBean实例 或 这个Bean是工厂Bean创建的,直接返回 if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; } //——————————以下都是 这个Bean实例是FactoryBean实例的情况 Object object = null; if (mbd == null) {//若根Bean定义为空,取这个BeanFactory所生产的实例 object = getCachedObjectForFactoryBean(beanName); } if (object == null) {//若取不到,那么手动取 FactoryBean<?> factory = (FactoryBean<?>) beanInstance;//把这个实例转化成一个FactoryBean // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) {//若根Bean定义为空,但是容器内有Bean定义 mbd = getMergedLocalBeanDefinition(beanName);//返回合并后的Bean定义 } boolean synthetic = (mbd != null && mbd.isSynthetic());//标记这个Bean定义是合并的 object = getObjectFromFactoryBean(factory, beanName, !synthetic);//从工厂Bean中取 } return object; } //判断给定的Bean是否被使用过 public boolean isBeanNameInUse(String beanName) { //若是别名 或 并非工厂bean生产出来的 或 被其他某个bean所依赖,那么判断其被使用过 return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName); } /** * Determine whether the given bean requires destruction on shutdown. * <p>The default implementation checks the DisposableBean interface as well as * a specified destroy method and registered DestructionAwareBeanPostProcessors. * @param bean the bean instance to check * @param mbd the corresponding bean definition * @see org.springframework.beans.factory.DisposableBean * @see AbstractBeanDefinition#getDestroyMethodName() * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor */ protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) { return (bean != null && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || hasDestructionAwareBeanPostProcessors())); } /** * Add the given bean to the list of disposable beans in this factory, * registering its DisposableBean interface and/or the given destroy method * to be called on factory shutdown (if applicable). Only applies to singletons. * @param beanName the name of the bean * @param bean the bean instance * @param mbd the bean definition for the bean * @see RootBeanDefinition#isSingleton * @see RootBeanDefinition#getDependsOn * @see #registerDisposableBean * @see #registerDependentBean */ protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null); if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { if (mbd.isSingleton()) { // Register a DisposableBean implementation that performs all destruction // work for the given bean: DestructionAwareBeanPostProcessors, // DisposableBean interface, custom destroy method. registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } else { // A bean with a custom scope... Scope scope = this.scopes.get(mbd.getScope()); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'"); } scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } } } //--------------------------------------------------------------------- // Abstract methods to be implemented by subclasses //--------------------------------------------------------------------- //标记是否包含Bean定义的方法 protected abstract boolean containsBeanDefinition(String beanName); //根据Bean名返回其BeanDefinition protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException; //根据指定的bean定义和bean名、参数,创建对象 protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException; }
总结:方法太多了,一个个介绍很浪费时间,不具体介绍。大体介绍一下吧。这个AbstractBeanFactory继承了支持工厂Bean注册的FactoryBeanRegistrySupport,并且实现了BeanFactory重要的第三级接口——ConfigurableBeanFactory。需要具体了解这个接口,可以去看我之前的接口分析——Spring源码分析——BeanFactory体系之接口详细分析 。ConfigurableBeanFactory是一个非常复杂的接口,继承了HierarchicalBeanFactory和SingletonBeanRegistry,主要实现了工厂创建、注册Bean、单例类注册等各种功能。
AbstractBeanFactory实现了ConfigurableBeanFactory接口的绝大多数方法,实现了Bean工厂的许多重要功能,如BeanDefinition、RootBeanDefinition、原型、单例相关的各种操作。
下面列出一些主要方法实现,其他的方法说明,可具体参照上文我贴出的大部分注释过的源码。
(1)、从容器中获取bean的方法——doGetBean:
@SuppressWarnings("unchecked") protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name);//在aliasMap中取得的标准名 Object bean; // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName);//首先在单例集合中取 if (sharedInstance != null && args == null) {//如果取得到,没有指定参数 if (logger.isDebugEnabled()) {//若Log允许调试 if (isSingletonCurrentlyInCreation(beanName)) {//若正准备创建,输出日志 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } ////根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { if (isPrototypeCurrentlyInCreation(beanName)) {//如果正在被创建,就抛出异常 throw new BeanCurrentlyInCreationException(beanName); } BeanFactory parentBeanFactory = getParentBeanFactory();//取本容器的父容器 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {//若存在父容器,且本容器不存在对应的Bean定义 String nameToLookup = originalBeanName(name);//取原始的Bean名 if (args != null) {//若参数列表存在 // 那么用父容器根据原始Bean名和参数列表返回 return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // 参数列表不要求,那就直接根据原始名称和要求的类型返回 return parentBeanFactory.getBean(nameToLookup, requiredType); } } //如果不需要类型检查,标记其已经被创建 if (!typeCheckOnly) { markBeanAsCreated(beanName); } //根据beanName取其根Bean定义 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); String[] dependsOn = mbd.getDependsOn();//得到这个根定义的所有依赖 if (dependsOn != null) { for (String dependsOnBean : dependsOn) { getBean(dependsOnBean);//注册这个Bean //注册一个Bean和依赖于它的Bean(后参数依赖前参数) registerDependentBean(dependsOnBean, beanName); } } // 如果Bean定义是单例,就在返回单例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } } }); //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //如果是原型 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 '" + scopeName + "'"); } try {//根据范围创建实例 Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args);//原型创建前,与当前线程绑定 } finally { ////原型创建后,与当前线程解除绑定 afterPrototypeCreation(beanName); } } }); //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 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); } } } //判断要求的类型是否和Bean实例的类型正在匹配 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { try { return getTypeConverter().convertIfNecessary(bean, requiredType);//转换类型,不抛出异常就说明类型匹配 } 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; }
下面对这个方法进行简要的解释:
<1>、这个方法形参为final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly,分别表示Bean的名称、要求返回的Bean的类型、取Bean时提供的参数数组 以及 是否需要类型检查。哦
<2>、final String beanName = transformedBeanName(name); 这个方法是从aliasMap中取得对应的标准名。方法实现是,首先去掉name的 FACTORY_BEAN_PREFIX 前缀(如果是工厂Bean本身,那么Bean名有这个前缀),然后调用SimpleAliasRegistry的canonicalName方法。上篇博客已经介绍过SimpleAliasRegistry了,这里贴一下这个方法的源码:
/* * 根据name这个Key,在aliasMap中不断循环的取对应的value,如果取得到,就继续根据这个value取值,不断循环继续。 * 直到取不到,就把这个在aliasMap中无对应值的key返回。这个动作,叫规范名 */ public String canonicalName(String name) { String canonicalName = name; //规范名 // Handle aliasing... String resolvedName;//已解析名 do { resolvedName = this.aliasMap.get(canonicalName);//aliasMap中规范名对应的值赋值给已解析名 if (resolvedName != null) {//如果已解析名存在(即规范名在aliasMap中有对应的值) canonicalName = resolvedName; // 这个已解析名赋值给标准名 } } while (resolvedName != null);//不断循环,直到已解析名不存在 return canonicalName; }
<3>、首先根据标准名beanName,在单例缓存中取对应的Bean:Object sharedInstance = getSingleton(beanName);
<4>、如果取得到,且args为空,根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例:bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);然后结束整个方法。这个方法源码如下:
//根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { //如果这个Bean是工厂Bean创建的 且 这个Bean实例并不是FactoryBean实例,抛异常 if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); } //如果这个Bean实例并不是FactoryBean实例 或 这个Bean是工厂Bean创建的,直接返回 if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; } //——————————以下都是 这个Bean实例是FactoryBean实例的情况 Object object = null; if (mbd == null) {//若根Bean定义为空,取这个BeanFactory所生产的实例 object = getCachedObjectForFactoryBean(beanName); } if (object == null) {//若取不到,那么手动取 FactoryBean<?> factory = (FactoryBean<?>) beanInstance;//把这个实例转化成一个FactoryBean // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) {//若根Bean定义为空,但是容器内有Bean定义 mbd = getMergedLocalBeanDefinition(beanName);//返回合并后的Bean定义 } boolean synthetic = (mbd != null && mbd.isSynthetic());//标记这个Bean定义是合并的 object = getObjectFromFactoryBean(factory, beanName, !synthetic);//从工厂Bean中取 } return object;
<5>、如果取不到、或 args 不为空(下面都是基于这个条件):
(如果对应的Bean正在被创建,就抛出异常)首先用父容器(如果本容器有的话)根据给出的形参取对应的Bean。
<6>、此时,判断,如果不需要类型检查,标记其已经被创建。
<7>、根据beanName取本地合并后的RootBeanDefinition(这个方法getMergedLocalBeanDefinition涉及到多层BeanDefinition相关的调用),然后检查一下。然后根据这个RootBeanDefinition,注册这个Bean和它的所有依赖。
<8>、如果这个RootBeanDefinition是单例,先根据beanName从单例缓存中取,取不到就创建一个匿名内部Bean工厂,创建一个单例,直接结束方法。
<9>、如果这个RootBeanDefinition是原型,就直接创建一个Bean返回,并在创建前把beanName与当前线程绑定,创建后解绑。
<10>、如果这个RootBeanDefinition既不是单例,又不是原型,那么根据这个RootBeanDefinition定义的范围Scope,直接创建一个scopedInstance。
<11>、若这个scopedInstance为工厂Bean,就得到它创建的实例,否则得到它自身。
<12>、对<9>或<11>中最后产生的Bean就进行一次检查,要求这个产生的Bean的类型是否和Bean实例的类型匹配,不匹配就抛出异常。
以上就是这个doGetBean方法了。其他的方法分析可参照上文的源码。