3.2spring源碼系列----循環依賴源碼分析

首先,咱們在3.1 spring5源碼系列--循環依賴 之 手寫代碼模擬spring循環依賴 中手寫了循環依賴的實現. 這個實現就是模擬的spring的循環依賴. 目的是爲了更容易理解spring源碼.html

下面咱們就進入正題, 看看spring的循環依賴源碼.spring

 

1、getBean總體流程

 

目標很明確了, 就是要看看spring如何解決循環依賴的. 設計模式

代碼入口是refresh()#finishBeanFactoryInitialization(beanFactory);緩存

2、拆解研究流程中的每一步

調用方法beanFactory.preInstantiateSingletons();實例化剩餘的單例bean. 爲何是剩餘的?很顯然咱們在上面已經實例化一部分了.好比配置類, postProcessor等.mvc

2.1 入口

 1 @Override
 2     public void preInstantiateSingletons() throws BeansException { 3 if (logger.isTraceEnabled()) { 4 logger.trace("Pre-instantiating singletons in " + this); 5  } 6 7 8 // 獲取容器中全部bean定義的名字 9 List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); 10 11 // Trigger initialization of all non-lazy singleton beans... 12 /** 13 * 第一步: 循環bean定義的name 14 */ 15 for (String beanName : beanNames) { 16 // 獲取bean定義 17 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); 18 // 生產bean定義的條件: 不是抽象的, 是單例的, 不是懶加載的. 符合這個標準的, 最後纔會調用getBean()生產bean 19 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { 20 // 這裏判斷是否是工廠bean, 這裏和BeanFactory不是一個意思, 判斷當前這個bean是否實現了beanFactory的接口 21 if (isFactoryBean(beanName)) { 22 Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); 23 if (bean instanceof FactoryBean) { 24 final FactoryBean<?> factory = (FactoryBean<?>) bean; 25  boolean isEagerInit; 26 if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { 27 isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) 28 ((SmartFactoryBean<?>) factory)::isEagerInit, 29  getAccessControlContext()); 30  } 31 else { 32 isEagerInit = (factory instanceof SmartFactoryBean && 33 ((SmartFactoryBean<?>) factory).isEagerInit()); 34  } 35 if (isEagerInit) { 36 // 獲取bean 37  getBean(beanName); 38  } 39  } 40  } 41 else {
              // 第二步: 調用bean定義 42 getBean(beanName); 43 } 44 } 45 } 46 47 // Trigger post-initialization callback for all applicable beans... 48 /** 49 * 循環bean定義的name 50 */ 51 for (String beanName : beanNames) { 52 // 從緩存中獲得實例instance 53 Object singletonInstance = getSingleton(beanName); 54 if (singletonInstance instanceof SmartInitializingSingleton) { 55 final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; 56 if (System.getSecurityManager() != null) { 57 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { 58 smartSingleton.afterSingletonsInstantiated(); 59 return null; 60 }, getAccessControlContext()); 61 } 62 else { 63 smartSingleton.afterSingletonsInstantiated(); 64 } 65 } 66 } 67 }

首先, 循環bean定義, 這和咱們模擬spring循環的第一步是同樣的. 

第二步: 判斷從BeanDefinitionMap中取出來的這個bean是否知足生產bean的條件

咱們注意代碼註釋中, 生產bean定義的條件: 不是抽象的, 是單例的, 不是懶加載的. 符合這個標準的, 最後纔會調用getBean()生產beanapp

而後:調用getBean()

到目前爲止,咱們完成了上圖源碼圖的第一部分:異步

 

 

 2.2 建立bean前的準備工做

接下來看看getBean().doGetBean()方法ide

  1 protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
  2  @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { 3 4 // 第一步: 轉換bean name. 在這裏傳入進來的name多是別名, 也有多是工廠bean的name, 因此在這裏進行一個轉換 5 final String beanName = transformedBeanName(name); 6  Object bean; 7 8 // Eagerly check singleton cache for manually registered singletons. 9 // 第二步: 嘗試去緩存中獲取對象, 若是沒有獲取到就建立bean 10 Object sharedInstance = getSingleton(beanName); 11 if (sharedInstance != null && args == null) { 12 if (logger.isTraceEnabled()) { 13 //判斷當前類是不是正在建立中 14 if (isSingletonCurrentlyInCreation(beanName)) { 15 logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + 16 "' that is not fully initialized yet - a consequence of a circular reference"); 17  } 18 else { 19 logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); 20  } 21  } 22 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); 23  } 24 25 else { 26 // Fail if we're already creating this bean instance: 27 // We're assumably within a circular reference. 28 /** 29 * 判斷當前的bean是否是多例, 若是是這拋出異常  30 * 31 * 判斷當前這個bean是否是多例bean. 若是配置了@Scope("prototype") 就表示這是一個多例的bean 32 * spring 只能解決單例對象的setter注入的循環依賴, 不能解決構造器注入 33 * 34 * 若是是多例的bean, 當前正在建立bean, 也會拋出異常---這也是循環依賴的問題 35 */ 36 if (isPrototypeCurrentlyInCreation(beanName)) { 37 throw new BeanCurrentlyInCreationException(beanName); 38  } 39 40 /** 41 * 下面這段代碼是關於子父容器的, 只有spring mvc繼承自spring, 纔會有子父容器的問題. 42 */ 43 // Check if bean definition exists in this factory. 44 BeanFactory parentBeanFactory = getParentBeanFactory(); 45 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { 46 // Not found -> check parent. 47 String nameToLookup = originalBeanName(name); 48 if (parentBeanFactory instanceof AbstractBeanFactory) { 49 return ((AbstractBeanFactory) parentBeanFactory).doGetBean( 50  nameToLookup, requiredType, args, typeCheckOnly); 51  } 52 else if (args != null) { 53 // Delegation to parent with explicit args. 54 return (T) parentBeanFactory.getBean(nameToLookup, args); 55  } 56 else if (requiredType != null) { 57 // No args -> delegate to standard getBean method. 58 return parentBeanFactory.getBean(nameToLookup, requiredType); 59  } 60 else { 61 return (T) parentBeanFactory.getBean(nameToLookup); 62  } 63  } 64 65 /** 66 * 方法參數typeCheckOnly是用來判斷#getBean()方法時, 表示是否爲僅僅進行類型檢查, 67 * 若是不只僅作類型檢查, 而是建立bean對象, 則須要調用#markBeanAsCreated(String name) 68 * 69 */ 70 if (!typeCheckOnly) { 71  markBeanAsCreated(beanName); 72  } 73 74 try { 75 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 76  checkMergedBeanDefinition(mbd, beanName, args); 77 78 // Guarantee initialization of beans that the current bean depends on. 79 /** 80 * 如今有兩個bean1, bean2 , 加載的時候調用的是bean1, bean2. 但若是咱們想要bean2優先加載, 就使用@DependOn註解 81 * 用來解析帶有dependOn註解的類 82 */ 83 String[] dependsOn = mbd.getDependsOn(); 84 if (dependsOn != null) { 85 for (String dep : dependsOn) { 86 if (isDependent(beanName, dep)) { 87 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 88 "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); 89  } 90  registerDependentBean(dep, beanName); 91 try { 92  getBean(dep); 93  } 94 catch (NoSuchBeanDefinitionException ex) { 95 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 96 "'" + beanName + "' depends on missing bean '" + dep + "'", ex); 97  } 98  } 99  } 100 101 // Create bean instance. 102 /** 103 * 第三步: 建立單例bean實例 104 */ 105 if (mbd.isSingleton()) { // 處理單例bean 106 /** 107 * 這裏getSingleton()和上面的getSigleton不同, 上面的是從一級緩存中拿. 108 * 這個getSingleton()就辦了一件事: 將bean設置爲正在建立的狀態. 這個狀態很重要, 若是出現循環依賴, 發現bean正在建立, 就不會再建立了 109 */ 110 sharedInstance = getSingleton(beanName, () -> { 111 try { 112 return createBean(beanName, mbd, args); 113  } 114 catch (BeansException ex) { 115 // Explicitly remove instance from singleton cache: It might have been put there 116 // eagerly by the creation process, to allow for circular reference resolution. 117 // Also remove any beans that received a temporary reference to the bean. 118  destroySingleton(beanName); 119 throw ex; 120  } 121  }); 122 // 獲得bean實例對象 123 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 124  } 125 126 else if (mbd.isPrototype()) { // 處理多例bean 127 // It's a prototype -> create a new instance. 128 Object prototypeInstance = null; 129 try { 130 // 當前正在建立多例bean 131  beforePrototypeCreation(beanName); 132 // 執行建立bean 133 prototypeInstance = createBean(beanName, mbd, args); 134  } 135 finally { 136  afterPrototypeCreation(beanName); 137  } 138 // 獲取bean實例對象 139 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 140  } 141 142 else { // 處理其餘類型的bean 143 String scopeName = mbd.getScope(); 144 final Scope scope = this.scopes.get(scopeName); 145 if (scope == null) { 146 throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); 147  } 148 try { 149 Object scopedInstance = scope.get(beanName, () -> { 150  beforePrototypeCreation(beanName); 151 try { 152 return createBean(beanName, mbd, args); 153  } 154 finally { 155  afterPrototypeCreation(beanName); 156  } 157  }); 158 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 159  } 160 catch (IllegalStateException ex) { 161 throw new BeanCreationException(beanName, 162 "Scope '" + scopeName + "' is not active for the current thread; consider " + 163 "defining a scoped proxy for this bean if you intend to refer to it from a singleton", 164  ex); 165  } 166  } 167  } 168 catch (BeansException ex) { 169  cleanupAfterBeanCreationFailure(beanName); 170 throw ex; 171  } 172 } 

 

在這裏, 首先從緩存中獲取bean, 看緩存中是否已經存在了函數

 Object sharedInstance = getSingleton(beanName);

而後, 若是緩存中已經存在了,那麼久直接取出來. 代碼以下: post

    if (sharedInstance != null && args == null) {
            if (logger.isTraceEnabled()) { //判斷當前bean是不是正在建立中(單例bean) 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 + "'"); } } bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); }

若是是空, 就說明是第一次建立, 執行else的部分

首先, 判斷是不是正在建立的多例bean, 若是是正在建立的多例bean, 就拋出異常,

  已是正在建立了, 說明這至少是第二次了, 這裏處理的是單例bean的循環依賴, 不處理多例bean的循環依賴, 因此拋出異常

  對應的代碼是這一句

  

// Fail if we're already creating this bean instance:
 27             // We're assumably within a circular reference.
 28             /**
 29              * 判斷當前的bean是否是多例, 若是是這拋出異常
 30              *
 31              * 判斷當前這個bean是否是多例bean. 若是配置了@Scope("prototype") 就表示這是一個多例的bean
 32              * spring 只能解決單例對象的setter注入的循環依賴, 不能解決構造器注入
 33              *
 34              * 若是是多例的bean, 當前正在建立bean, 也會拋出異常---這也是循環依賴的問題
 35              */
 36             if (isPrototypeCurrentlyInCreation(beanName)) {
 37                 throw new BeanCurrentlyInCreationException(beanName); 38 }

 

那麼, 接下來就是首次建立bean. 首次建立的bean有三種狀況:

  第一種, 這個bean是單例的.

  第二種, 這個bean是多例的.

  第三種. 其餘類型

對應的代碼就是這一塊. 有行號, 能夠和上面一一對應上

// Create bean instance.
102                 /**
103                  * 第三步: 建立單例bean實例
104                  */
105                 if (mbd.isSingleton()) { // 處理單例bean
106                     /**
107                      * 這裏getSingleton()和上面的getSigleton不同, 上面的是從一級緩存中拿.
108                      * 這個getSingleton()就辦了一件事: 將bean設置爲正在建立的狀態. 這個狀態很重要, 若是出現循環依賴, 發現bean正在建立, 就不會再建立了
109                      */
110                     sharedInstance = getSingleton(beanName, () -> {
111                         try { 112 return createBean(beanName, mbd, args); 113 } 114 catch (BeansException ex) { 115 // Explicitly remove instance from singleton cache: It might have been put there 116 // eagerly by the creation process, to allow for circular reference resolution. 117 // Also remove any beans that received a temporary reference to the bean. 118 destroySingleton(beanName); 119 throw ex; 120 } 121 }); 122 // 獲得bean實例對象 123 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 124 } 125 126 else if (mbd.isPrototype()) { // 處理多例bean 127 // It's a prototype -> create a new instance. 128 Object prototypeInstance = null; 129 try { 130 // 當前正在建立多例bean 131 beforePrototypeCreation(beanName); 132 // 執行建立bean 133 prototypeInstance = createBean(beanName, mbd, args); 134 } 135 finally { 136 afterPrototypeCreation(beanName); 137 } 138 // 獲取bean實例對象 139 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 140 } 141 142 else { // 處理其餘類型的bean 143 String scopeName = mbd.getScope(); 144 final Scope scope = this.scopes.get(scopeName); 145 if (scope == null) { 146 throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); 147 } 148 try { 149 Object scopedInstance = scope.get(beanName, () -> { 150 beforePrototypeCreation(beanName); 151 try { 152 return createBean(beanName, mbd, args); 153 } 154 finally { 155 afterPrototypeCreation(beanName); 156 } 157 }); 158 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 159 } 160 catch (IllegalStateException ex) { 161 throw new BeanCreationException(beanName, 162 "Scope '" + scopeName + "' is not active for the current thread; consider " + 163 "defining a scoped proxy for this bean if you intend to refer to it from a singleton", 164 ex); 165 } 166 }

咱們的重點研究對象是單例bean. 因此,重點看單例bean的實現

105                 if (mbd.isSingleton()) { // 處理單例bean
106                     /**
107                      * 這裏getSingleton()和上面的getSigleton不同, 上面的是從一級緩存中拿.
108                      * 這個getSingleton()就辦了一件事: 將bean設置爲正在建立的狀態. 這個狀態很重要, 若是出現循環依賴, 發現bean正在建立, 就不會再建立了
109                      */
110                     sharedInstance = getSingleton(beanName, () -> {
111                         try {
112                             return createBean(beanName, mbd, args);
113                         }
114                         catch (BeansException ex) {
115                             // Explicitly remove instance from singleton cache: It might have been put there
116                             // eagerly by the creation process, to allow for circular reference resolution.
117                             // Also remove any beans that received a temporary reference to the bean.
118                             destroySingleton(beanName);
119                             throw ex;
120                         }
121                     });
122                     // 獲得bean實例對象
123                     bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
124                 }

這裏的重點是調用了getSingleton(beanName, FactoryObject); FactoryObject是一個接口. 定義了一個鉤子方法getObject(). 

這個接口在這裏這是進行了定義, 並不會執行. 何時執行呢? 後面調用的時候執行. 

下面來看看getSingleton()方法, 鉤子方法也是在這裏被調用的.

 1 public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
 2         Assert.notNull(beanName, "Bean name must not be null"); 3 synchronized (this.singletonObjects) { 4 // 第一步: 從一級緩存中獲取單例對象 5 Object singletonObject = this.singletonObjects.get(beanName); 6 if (singletonObject == null) { 7 if (this.singletonsCurrentlyInDestruction) { 8 throw new BeanCreationNotAllowedException(beanName, 9 "Singleton bean creation not allowed while singletons of this factory are in destruction " + 10 "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); 11  } 12 if (logger.isDebugEnabled()) { 13 logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); 14  } 15 // 第二步: 將bean添加到singletonsCurrentlyInCreation中, 表示bean正在建立 16  beforeSingletonCreation(beanName); 17 boolean newSingleton = false; 18 boolean recordSuppressedExceptions = (this.suppressedExceptions == null); 19 if (recordSuppressedExceptions) { 20 this.suppressedExceptions = new LinkedHashSet<>(); 21  } 22 try { 23 // 第三步: 這裏調用getObject()鉤子方法, 就會回調匿名函數, 調用singletonFactory的createBean() 24 singletonObject = singletonFactory.getObject(); 25 newSingleton = true; 26  } 27 catch (IllegalStateException ex) { 28 // Has the singleton object implicitly appeared in the meantime -> 29 // if yes, proceed with it since the exception indicates that state. 30 singletonObject = this.singletonObjects.get(beanName); 31 if (singletonObject == null) { 32 throw ex; 33  } 34  } 35 catch (BeanCreationException ex) { 36 if (recordSuppressedExceptions) { 37 for (Exception suppressedException : this.suppressedExceptions) { 38  ex.addRelatedCause(suppressedException); 39  } 40  } 41 throw ex; 42  } 43 finally { 44 if (recordSuppressedExceptions) { 45 this.suppressedExceptions = null; 46  } 47  afterSingletonCreation(beanName); 48  } 49 if (newSingleton) { 50  addSingleton(beanName, singletonObject); 51  } 52  } 53 return singletonObject; 54  } 55 }

這裏是調用getBean().

第一步: 去一級緩存中取成熟的單例bean. 若是拿到了, 就直接返回. 若是沒拿到. 那麼執行建立. 

第二步: 在建立以前, 先把這個bean放入到正在建立的單例bean集合中. 標記這個bean正在建立中

第三步: 就是調用鉤子方法getObject()了. 這個方法的方法體是在上面定義的. 其內容是去建立實例

            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; } });

這裏的代碼邏輯是完成了建立以前的邏輯

2.3 建立bean 

下面看看建立bean的過程

    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.
        BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { /** * 第一步: 實例化 * 這裏面的調用鏈很是深, 後面再看 * bean實例化有兩種方式 * 1. 使用反射: 使用反射也有兩種方式, * a. 經過無參構造函數 (默認的方式) * 從beanDefinition中能夠獲得beanClass, * ClassName = BeanDefinition.beanClass * Class clazz = Class.forName(ClassName); * clazz.newInstance(); * 這樣就能夠實例化bean了 * * b. 經過有參函數. * ClassName = BeanDefinition.beanClass * Class clazz = Class.forName(ClassName); * Constractor con = class.getConstractor(args....) * con.newInstance(); * * 2. 使用工廠 * 咱們使用@Bean的方式, 就是使用的工廠模式, 本身控制實例化過程 * */ instanceWrapper = createBeanInstance(beanName, mbd, args); } // 這裏使用了裝飾器的設計模式 final Object bean = instanceWrapper.getWrappedInstance(); Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. // 容許後置處理器修改已經合併的beanDefinition  synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } /** * 緩存單例bean到三級緩存中, 以防止循環依賴 * 判斷是不是早期引用的bean, 若是是, 則容許提早暴露引用
     * * 判斷是否可以早起暴露的條件 * 1. 是單例 * 2. 容許循環依賴 * 3. 正在建立的bean */ boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } // 把咱們的早期對象包裝成一個singletonFactory對象, 該對象提供了getObject()方法, 把靜態的bean放到三級緩存中去了. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. Object exposedObject = bean; try { // 第二步:填充屬性, 給屬性賦值(調用set方法) 這裏也是調用的後置處理器 populateBean(beanName, mbd, instanceWrapper); // 第三步: 初始化. exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } /** * 初始化完成之後, 判斷是不是早期的對象 * 是循環依賴. 纔會走進這裏來 */ if (earlySingletonExposure) { // 去緩存中獲取到咱們的對象 因爲傳遞的allowEarlyReference是false, 要求只能在一級二級緩存中取 // 正常的普通的bean(不存在循環依賴的bean) 建立的過程當中, 不會把三級緩存提高到二級緩存中. Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(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."); } } } } // Register bean as disposable. try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }

首先, 實例化bean, 實例化的方式有兩種. 一種是經過反射, 另外一種是經過動態代理

/**
             * 第一步: 實例化
             * 這裏面的調用鏈很是深, 後面再看
             * bean實例化有兩種方式
             * 1. 使用反射:  使用反射也有兩種方式,
             *         a. 經過無參構造函數 (默認的方式)
             *             從beanDefinition中能夠獲得beanClass,
             *             ClassName = BeanDefinition.beanClass
             *             Class clazz = Class.forName(ClassName);
             *             clazz.newInstance();
             *             這樣就能夠實例化bean了
             *
             *         b. 經過有參函數.
             *            ClassName = BeanDefinition.beanClass
             *             Class clazz = Class.forName(ClassName);
             *             Constractor con = class.getConstractor(args....)
             *             con.newInstance();
             *
             * 2. 使用工廠
             *         咱們使用@Bean的方式, 就是使用的工廠模式, 本身控制實例化過程
             *
             */
            instanceWrapper = createBeanInstance(beanName, mbd, args);

 

判斷是不是早期暴露的bean. 知足早期暴露的bean的三個條件是

1. 是單例的

2. 容許循環依賴

3. bean已是處在正在建立中的行列了.

        /* 判斷是否可以早起暴露的條件
         *     1. 是單例
         *     2. 容許循環依賴
         *     3. 正在建立的bean
         */
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); 

建立bean的第二步: 屬性賦值

// 第二步:填充屬性, 給屬性賦值(調用set方法)  這裏也是調用的後置處理器
populateBean(beanName, mbd, instanceWrapper);

在這裏會判斷, 是否帶有@Autowired的屬性. 分爲兩種一種是Name,一種是Type

@SuppressWarnings("deprecation")  // for postProcessPropertyValues
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        if (bw == null) { if (mbd.hasPropertyValues()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 判斷屬性是否有Autowired註解 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); // Autowired是根據名字或者根據類型 if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } ...... }

若是按照名字注入

  protected void autowireByName(
            String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { if (containsBean(propertyName)) { // 調用getBean Object bean = getBean(propertyName); pvs.add(propertyName, bean); registerDependentBean(propertyName, beanName); if (logger.isTraceEnabled()) { logger.trace("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } }

會再次調用getBean方法. 構建bean. 這是就有可能出現循環依賴了. 

按類型注入也是同樣的. 

只是解析bean的方式不一樣.

 

建立bean的第三步: 初始化

 // 第三步: 初始化.
 exposedObject = initializeBean(beanName, exposedObject, mbd);

在初始化bean的時候, 會調用不少的aware. 還會調用init-method方法. 以及bean的後置處理器.

 

第四步:刪除實例化和靜態方法在緩存中的數據

     /**
         * 初始化完成之後, 判斷是不是早期的對象
         * 是循環依賴. 纔會走進這裏來
          */
        if (earlySingletonExposure) {
            // 去緩存中獲取到咱們的對象 因爲傳遞的allowEarlyReference是false, 要求只能在一級二級緩存中取
            // 正常的普通的bean(不存在循環依賴的bean) 建立的過程當中, 不會把三級緩存提高到二級緩存中.
            Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(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."); } } } }
removeSingletonIfCreatedForTypeCheckOnly調用方法, 刪除緩存.

這既是getBean()整個的過程. 中間還有不少細節, 沒有往裏面深刻的看, 由於spring代碼很是的深, 看的太深就忘了咱們的目標了. 結合以前手寫的spring循環依賴的思想看, 仍是能夠看得懂的. 

 

 

三. 接下來有幾個問題

問題1: 爲何須要二級緩存和三級緩存?

二級緩存用來存放早期的bean, 也就是沒有被屬性賦值和初始化的bean
三級緩存的主要做用是用來解耦. 解耦後異步調用, 三級緩存中保存的是鉤子方法,也就是一個接口。在使用的時候調用bean的後置處理器

 

問題2:有沒有解決構造函數的循環依賴

答案是沒有. 由於構造函數是在實例化的時候構建的. 這個時候bean都尚未建立, 因此沒有辦法處理循環依賴.若是出現構造函數的循環依賴, 是會直接報錯的..

 

問題3:有沒有解決多例下的循環依賴

也是沒有的, 由於咱們會判斷, 若是是多例, 那麼會拋出異常

 1             /**
 2              * 第二步: 判斷當前bean是不是正在建立中的多例bean, 若是是就拋出異常
 3              *
 4              * 2. 判斷當前這個bean是否是多例bean. 若是配置了@Scope("prototype") 就表示這是一個多例的bean
 5              * spring 只能解決單例對象的setter注入的循環依賴, 不能解決構造器注入
 6              *
 7              * 若是是多例的bean, 當前正在建立bean, 也會拋出異常---這也是循環依賴的問題
 8              */
 9             if (isPrototypeCurrentlyInCreation(beanName)) {
10                 throw new BeanCurrentlyInCreationException(beanName); 11 } 
相關文章
相關標籤/搜索