/** * Return an instance, which may be shared or independent, of the specified bean. * @param name the name of the bean to retrieve * @param requiredType the required type of the bean to retrieve * @param args arguments to use when creating a bean instance using explicit arguments * (only applied when creating a new instance as opposed to retrieving an existing one) * @param typeCheckOnly whether the instance is obtained for a type check, * not for actual use * @return an instance of the bean * @throws BeansException if the bean could not be created */ @SuppressWarnings("unchecked") protected <T> T doGetBean(final String name, @Nullablefinal Class<T> requiredType, @Nullablefinal Object[] args, boolean typeCheckOnly)throws BeansException { // 先获取出bean的名字 finalStringbeanName= transformedBeanName(name); // 定义一个bean Object bean;
// Eagerly check singleton cache for manually registered singletons. //org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean),从DefaultSinglonBeanRegisttry中的singletonObjects根据bean获取出来Object. ObjectsharedInstance= getSingleton(beanName); // 获取出来的bean不是null,并且传入进来的 args是null的话,就会进入到if逻辑中. if (sharedInstance != null && args == null) { // 根据 trace级别的log来进行打印 if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } //一: 如果name不是bull并且是&开头的话,满足这个条件, /** 如果满足上面的条件的话 1: 如果是 beanInstance(sharedInstance) 是NullBean的话,就会直接返回回去. 2: 如果1没有return回去的话,判断是不是FactoryBean,如果不是的话,就会抛一个BeanIsNotAFactoryException异常出来. 3: 1和2都不满足的话,就会判断mbd是不是null,很明显我们这里传入进去的是null,如果不是null的话, 就会 mbd.isFactoryBean = true; 最后返回 beanInstance; */ //如果不是满足 一 的话,判断不是FactoryBean的话,就会直接返回回去.如果是的哈,就会继续往下走 //定义一个Object object,如果RootBeanDefinition mbd是null的话,就会getCachedObjectForFactoryBean方法,否则的话,就会mbd.isFactoryBean = true; //如果object不是null的话,就直接返回. 是null的话,就会先将beanInstance强转为FactoryBean, //然后看到是null的话,就会调用getObjectFromFactoryBean这个方法,从名字上看,就是从FactoryBean中获取出object. // 如果是走了这里的话,就不会走else里面的含有 createBean这个方法的 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); }
else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. // 判断 beanName是不是正在创建,如果是正在创建的话,那么这里就会抛出异常来. //Object curVal = this.prototypesCurrentlyInCreation.get();使用的是ThreadLocal来存储正在创建的bean信息.这里获取出来了,判断.如果是一样的话,那么就说名字这个bean是正在创建的. if (isPrototypeCurrentlyInCreation(beanName)) { thrownewBeanCurrentlyInCreationException(beanName); }
// Check if bean definition exists in this factory. // 获取 parent BeanFacotry. BeanFactoryparentBeanFactory= getParentBeanFactory(); // 获取出来的parentBeanFactory不是null的话并且beanFactoy中存放bd的集合中没有这个beanName if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. // 这里也是获取beanName的 StringnameToLookup= originalBeanName(name); // 如果parentBeanFactroy是AbstractBeanFactory的话 // 强转调用doGetBean方法,直接返回的. if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } elseif (args != null) { // Delegation to parent with explicit args. // 如果parentBeanFactory不是AbstractBeanFactory并且args不是null // 直接调用getBean方法返回. 这里传入进去的是 beanName + args return (T) parentBeanFactory.getBean(nameToLookup, args); } elseif (requiredType != null) { // No args -> delegate to standard getBean method. // 这里调用的getBean方法,传入进去的是 beanName + Class return parentBeanFactory.getBean(nameToLookup, requiredType); } else { // 这里是直接根据beanName或取出来 return (T) parentBeanFactory.getBean(nameToLookup); } } // typeCheckOnly是false才会走进这个if里面 if (!typeCheckOnly) { // 标记这个bean已创建了 markBeanAsCreated(beanName); }
else { // 该条件里面是对既不是单例,也不是多例的的处理. //显示获取出scope这个注解的值,根据获取出来的值从 scopes 这个Map集合中获取. StringscopeName= mbd.getScope(); finalScopescope=this.scopes.get(scopeName); //如果从map集合中获取出来的值是null的话,那么这里就会抛出一个异常来. if (scope == null) { thrownewIllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { // TODO get()方法阅读 ObjectscopedInstance= scope.get(beanName, () -> { // 这里的beforePrototypeCreation/createBean/getObjectForBeanInstance //可以很明显的看到是和上面的多例的逻辑相似的. 不同的是,这里还多走了一个scope.get方法. beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { thrownewBeanCreationException(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"isInstance, ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } }
// Check if required type matches the type of the actual bean instance. // requiredType不是null,判断调用class.isInstance()方法判断这个class是不是和这个bean相符合 if (requiredType != null && !requiredType.isInstance(bean)) { try { //满足的话,可以看到这行代码是在做创建bean的操作. TODO: 具体的阅读需要看其底层的代码走向 TconvertedBean= getTypeConverter().convertIfNecessary(bean, requiredType); // 如果获取出来的 bean是null的话,就抛出一个异常来. if (convertedBean == null) { thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } //如果不是null的话,这里就返回. return convertedBean; } catch (TypeMismatchException ex) { if (logger.isTraceEnabled()) { logger.trace("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } // 返回bean return (T) bean; }
createBean方法
//--------------------------------------------------------------------- // Implementation of relevant AbstractBeanFactory template methods //--------------------------------------------------------------------- /** * Central method of this class: creates a bean instance, * populates the bean instance, applies post-processors, etc. * @see #doCreateBean */ @Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } // 将传入进来的bd给赋值给mbdToUse. RootBeanDefinitionmbdToUse= mbd; // 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. // 这里获取mbd的class返回回来 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); //如果resolvedClass不是null,mbd的hasBeanClass是false(也就是没有beanClass),mbd调用的beanClassName不是null的情况,就会走到下面的这个方法中 if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { // new 一个bd出来 mbdToUse = newRootBeanDefinition(mbd); // 给bd设置上 resolvedClass mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { // 重写的方法 mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { thrownewBeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. // mbd.beforeInstantiationResolved是true就会满足条件,代码继续往下走.还有判断条件都好理解. //主要看applyBeanPostProcessorsBeforeInstantiation方法,该方法先获取出全部的 beanPostProcessors,然后迭代集合,如果是InstantiationAwareBeanPostProcessor接口的子类的话,就会强转走postProcessBeforeInstantiation方法. 最后返回一个bean,该bean是有可能是null的. //如果是null的话,就不会走到applyBeanPostProcessorsAfterInitialization方法 //如果不是null,救会走这个方法.所以我们接着看这个方法. // applyBeanPostProcessorsAfterInitialization方法:获取出全部的BeanPostProcessors,然后迭代,挨个调用其postProcessAfterInitialization方法,最后返回bean回去 Objectbean= resolveBeforeInstantiation(beanName, mbdToUse); // 如果bean不是null的话,就直接返回掉. if (bean != null) { return bean; } } catch (Throwable ex) { thrownewBeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { // 调用 doCreateBean() 返回一个bean,最后给这个bean返回回去(如果没出任何异常的情况下). ObjectbeanInstance= doCreateBean(beanName, mbdToUse, args); if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { // A previously detected exception with proper bean creation context already, // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. throw ex; } catch (Throwable ex) { thrownewBeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } }
doCreateBean方法
该方法就是真正创建bean的方法
/** * Actually create the specified bean. Pre-creation processing has already happened * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks. * <p>Differentiates between default bean instantiation, use of a * factory method, and autowiring a constructor. * @param beanName the name of the bean * @param mbd the merged bean definition for the bean * @param args explicit arguments to use for constructor or factory method invocation * @return a new instance of the bean * @throws BeanCreationException if the bean could not be created * @see #instantiateBean * @see #instantiateUsingFactoryMethod * @see #autowireConstructor */ protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final@Nullable Object[] args) throws BeanCreationException {
// Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { thrownewBeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } }
// Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. booleanearlySingletonExposure= (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); }
if (earlySingletonExposure) { ObjectearlySingletonReference= getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } elseif (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = newLinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { thrownewBeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); } } } }