@SuppressWarnings("unchecked") protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { // 提取对应的 beanName finalStringbeanName= transformedBeanName(name); Object bean;
// Eagerly check singleton cache for manually registered singletons. /** 检查缓存中或者实例工厂中是否有对应的实例 为什么首先会使用这段代码呢,因为在创建单例 bean 的时候会存在依赖注入的情况, 而在创建依赖的时候为了避免循环依赖,Spring 创建 bean 的原则是不等 bean 创建 完成就会将创建的 bean 的 ObjectFactory 提前曝光,也就是将 ObjectFactory 加入 缓存中,一旦下个 bean 创建时候需要依赖上个 bean 则直接使用 ObjectFactory **/ ObjectsharedInstance= getSingleton(beanName); if (sharedInstance != null && args == null) { if (logger.isDebugEnabled()) { 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 + "'"); } } // 返回对应的实例,有时候存在诸如 BeanFactory 的情况并不是直接返回实例本身而是返回指定方法返回的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); }
else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. /** 只有在单例情况才会尝试解决依赖循环,原型模型情况,如果存在 A 中有 B 的熟悉,B 中有 A 的属性,那么当依赖注入的时候,就会产生当 A 还未创建完的时候 因为对于 B 的创建再次返回创建 ,造成依赖循环,也就是下面的情况 **/ if (isPrototypeCurrentlyInCreation(beanName)) { thrownewBeanCurrentlyInCreationException(beanName); }
// Check if bean definition exists in this factory. BeanFactoryparentBeanFactory= getParentBeanFactory(); // 如果 beanDefinitionMap 中也就是在所有已经加载的类中不包括 beanName 则 // 尝试从 parentBeanFactory 中检测 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. StringnameToLookup= originalBeanName(name); // 递归到 BeanFactory 中寻找 if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } }
// 如果不是仅仅做类型检查则是创建 bean,这里要进行记录 if (!typeCheckOnly) { markBeanAsCreated(beanName); }
// Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); // 若存在依赖则需要递归实例化依赖的 bean if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { thrownewBeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } // 缓存依赖调用 registerDependentBean(dep, beanName); getBean(dep); } }
// Create bean instance. // 实例化依赖的 bean 后便可以实例化 mbd 本身了 // singleton 模式的创建 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, newObjectFactory<Object>() { @Override public Object getObject()throws BeansException { 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); }
// Don't let calling code try to dereference the factory if the bean isn't a factory. // 如果指定的 name 是工厂相关(以 & 为前缀)且 beanInstance 又不是 FactoryBean 类型则验证不通过 if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { thrownewBeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); }
// 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. // 现在我们有了个 bean 的实例,这个实例可能会是正常的 bean 或者 FactoryBean // 如果是 FactoryBean 我们使用它创建实例,但如果用户想要直接获取工厂实例而不是工程对应的 // getObject 方法对应的实例那么传入的 name 应该包含前缀 & if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; }
// 加载 FactoryBean Objectobject=null; if (mbd == null) { // 尝试从缓存中加载 bean object = getCachedObjectForFactoryBean(beanName); } if (object == null) { // Return bean instance from factory. // 到这里已经明确指定 beanInstance 一定是 FactoryBean 类型 FactoryBean<?> factory = (FactoryBean<?>) beanInstance; // Caches object obtained from FactoryBean if it is a singleton. // containsBeanDefinition 检测 beanDefinitionMap 中也就是在所有已经加载的类中 // 检测是否定义 beanName if (mbd == null && containsBeanDefinition(beanName)) { // 将存储 XML 配置文件的 GernericBeanDefinition 转换为 RootBeanDefinition, // 如果指定 BeanName 是子 Bean 的话同时会合并父类的相关属性 mbd = getMergedLocalBeanDefinition(beanName); } // 是否是用户定义而不是应用程序本身定义的 booleansynthetic= (mbd != null && mbd.isSynthetic()); object = getObjectFromFactoryBean(factory, beanName, !synthetic); } return object; }
// Do not accept a null value for a FactoryBean that's not fully // initialized yet: Many FactoryBeans just return null then. if (object == null && isSingletonCurrentlyInCreation(beanName)) { thrownewBeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } return object; }
// 实例化依赖的 bean 后便可以实例化 mbd 本身了 // singleton 模式的创建 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, newObjectFactory<Object>() { @Override public Object getObject()throws BeansException { 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); }
sharedInstance = getSingleton(beanName, newObjectFactory<Object>() { @Override public Object getObject()throws BeansException { 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; } } });
// Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. // 锁定 class,根据设置的 class 属性或者根据 className 来解析 Class Class<?> resolvedClass = resolveBeanClass(mbd, beanName); // 1 // 如果解析成功则 clone RootBeanDefinition 并且设置其 bean 类为解析之后的 class if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = newRootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }
publicvoidprepareMethodOverrides()throws BeanDefinitionValidationException { // Check that lookup methods exists. MethodOverridesmethodOverrides= getMethodOverrides(); if (!methodOverrides.isEmpty()) { Set<MethodOverride> overrides = methodOverrides.getOverrides(); synchronized (overrides) { for (MethodOverride mo : overrides) { prepareMethodOverride(mo); } } } }
protectedvoidprepareMethodOverride(MethodOverride mo)throws BeanDefinitionValidationException { // 获取对应类中对应方法名的个数 intcount= ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName()); if (count == 0) { thrownewBeanDefinitionValidationException( "Invalid method override: no method with name '" + mo.getMethodName() + "' on class [" + getBeanClassName() + "]"); } elseif (count == 1) { // Mark override as not overloaded, to avoid the overhead of arg type checking. // 标记 MethoOverride 暂未被覆盖,避免参数类型检查的开销 mo.setOverloaded(false); } }