1. 程式人生 > >Spring源碼閱讀(二)

Spring源碼閱讀(二)

函數 source fin gin pri remove relation boolean only

我們先看AbstractBeanFactory.getBean方法,這個方法通過bean名稱類型等信息獲取類實例,如果實例不存在則生產。

    //---------------------------------------------------------------------
    // Implementation of BeanFactory interface
    //---------------------------------------------------------------------

    @Override
    public Object getBean(String name) throws
BeansException { return doGetBean(name, null, null, false); }

關鍵方法doGetBean解讀如下

    /**
     * Return an instance, which may be shared or independent, of the specified bean.
     * 返回一個共享或獨立實例(單例或者多實例)
     * @param name the name of the bean to retrieve
     * bean名稱
     * @param requiredType the required type of the bean to retrieve
     * 期望返回的bean類型
     * 
@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 * 返回bean實例 * @throws BeansException if the bean could not be created */ @SuppressWarnings("unchecked") protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { // bean名稱轉換,包括別名轉換和&前綴處理(&前綴用於工廠類) final String beanName = transformedBeanName(name); Object bean; // Eagerly check singleton cache for manually registered singletons. // 單例模式下優先使用已經創建的實例,已經在創建中則等待 Object sharedInstance = 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 + "‘"); } } bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // Fail if we‘re already creating this bean instance: // We‘re assumably within a circular reference. // 防止類環形依賴創建時出現死鎖 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // Check if bean definition exists in this factory. // 檢查父工廠是否存在這個類實例 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } else 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); } } // 實例創建前上鎖 if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { // 獲取bean配置,這裏會把配置轉化為RootBeanDefinition final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // 檢查配置是否為抽象類 checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. // 優先加載依賴類 String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { 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); getBean(dep); } } // Create bean instance. // 創建單例 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; } }); // 1、 如果有其他類依賴此類,需要進行通知 // 2、 如果此類是工廠類,一般需要調用工廠方法返回類實例,而不是直接返回工廠類 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 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; }

關鍵代碼getSingleton下一講繼續研究。

Spring源碼閱讀(二)