前言:在【spring源碼分析】IOC容器初始化(三)中已經分析了BeanDefinition註冊以前的一些準備工做,下面將進入BeanDefinition註冊的核心流程。
html
1 //DefaultBeanDefinitionDocumentReader 2 protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { 3 // 進行bean標籤解析 4 // 若是解析成功,則返回BeanDefinitionHolder,BeanDefinitionHolder爲name和alias的BeanDefinition對象 5 // 若是解析失敗,則返回null 6 BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); 7 if (bdHolder != null) { 8 // 進行標籤處理,主要對bean標籤的相關屬性進行處理 如: p:name="測試用例" 9 bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); 10 try { 11 // 註冊BeanDefinition 12 // Register the final decorated instance. 13 BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); 14 } catch (BeanDefinitionStoreException ex) { 15 getReaderContext().error("Failed to register bean definition with name '" + 16 bdHolder.getBeanName() + "'", ele, ex); 17 } 18 // 發出響應時間,通知監聽器,已完成該bean標籤的解析 19 // Send registration event. 20 getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); 21 } 22 }
前面分析瞭如何解析bean標籤的默認屬性,在進行BeanDefinition註冊以前,還需對bean標籤的相關屬性進行處理,第9行代碼處。node
1 public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder) { 2 return decorateBeanDefinitionIfRequired(ele, definitionHolder, null); 3 } 4 5 public BeanDefinitionHolder decorateBeanDefinitionIfRequired( 6 Element ele, BeanDefinitionHolder definitionHolder, @Nullable BeanDefinition containingBd) { 7 8 // 解析完成後的返回值,封裝了其自定義屬性的BeandefinitionHolder 9 BeanDefinitionHolder finalDefinition = definitionHolder; 10 11 // #1.遍歷屬性,查看是否有適用於裝飾的屬性 12 // Decorate based on custom attributes first. 13 NamedNodeMap attributes = ele.getAttributes(); 14 for (int i = 0; i < attributes.getLength(); i++) { 15 Node node = attributes.item(i); 16 finalDefinition = decorateIfRequired(node, finalDefinition, containingBd); 17 } 18 19 // #2.遍歷子節點,查看是否有適用於裝飾的子節點 20 // Decorate based on custom nested elements. 21 NodeList children = ele.getChildNodes(); 22 for (int i = 0; i < children.getLength(); i++) { 23 Node node = children.item(i); 24 if (node.getNodeType() == Node.ELEMENT_NODE) { 25 finalDefinition = decorateIfRequired(node, finalDefinition, containingBd); 26 } 27 } 28 return finalDefinition; 29 }
分析:spring
這裏代碼邏輯比較簡單,就是遍歷節點的屬性或子節點,檢查是否須要裝飾的節點,如直接在bean標籤裏對屬性賦值:p:name="XXX"。其核心點在第16行處與第25行處。緩存
BeanDefinitionParserDelegate#decorateIfRequired併發
1 public BeanDefinitionHolder decorateIfRequired( 2 Node node, BeanDefinitionHolder originalDef, @Nullable BeanDefinition containingBd) { 3 4 // 首先獲取自定義標籤的命名空間 5 String namespaceUri = getNamespaceURI(node); 6 // 過濾掉默認的命名空間,由於這裏是自定義空間的解析,默認命名空間上面已經進行了解析 7 if (namespaceUri != null && !isDefaultNamespace(namespaceUri)) { 8 // 經過命名空間獲取對應的空間處理器 9 NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); 10 if (handler != null) { 11 // 進行裝飾處理 在SimplePropertyNamespaceHandler處理器中 12 BeanDefinitionHolder decorated = 13 handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd)); 14 if (decorated != null) { 15 return decorated; 16 } 17 } else if (namespaceUri.startsWith("http://www.springframework.org/")) { 18 error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node); 19 } else { 20 // A custom namespace, not to be handled by Spring - maybe "xml:...". 21 if (logger.isDebugEnabled()) { 22 logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]"); 23 } 24 } 25 } 26 return originalDef; 27 }
分析:app
SimplePropertyNamespaceHandler#decorateide
1 public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { 2 // 若是當前節點是屬性節點 3 if (node instanceof Attr) { 4 Attr attr = (Attr) node; 5 // 獲取name、value屬性 6 String propertyName = parserContext.getDelegate().getLocalName(attr); 7 String propertyValue = attr.getValue(); 8 // 獲取bean的propertyValues集合 9 MutablePropertyValues pvs = definition.getBeanDefinition().getPropertyValues(); 10 // 若是已經存在屬性了,則報錯 11 if (pvs.contains(propertyName)) { 12 parserContext.getReaderContext().error("Property '" + propertyName + "' is already defined using " + 13 "both <property> and inline syntax. Only one approach may be used per property.", attr); 14 } 15 // 若是屬性name以-ref結尾,則須要進行解析,不然直接加入MutablePropertyValues集合中 16 if (propertyName.endsWith(REF_SUFFIX)) { 17 propertyName = propertyName.substring(0, propertyName.length() - REF_SUFFIX.length()); 18 pvs.add(Conventions.attributeNameToPropertyName(propertyName), new RuntimeBeanReference(propertyValue)); 19 } 20 else { 21 pvs.add(Conventions.attributeNameToPropertyName(propertyName), propertyValue); 22 } 23 } 24 // 返回已經封裝了property屬性的BeanDefinitionHolder 25 return definition; 26 }
分析:函數
其實這段代碼的邏輯也比較簡單,就是獲取解析節點的name、value屬性,而後放入MutablePropertyValues集合中。源碼分析
1 public static void registerBeanDefinition( 2 BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) 3 throws BeanDefinitionStoreException { 4 5 // 註冊beanName 6 // Register bean definition under primary name. 7 String beanName = definitionHolder.getBeanName(); 8 // 調用DefaultListableBeanFactory#registerBeanDefinition方法進行bean註冊 9 registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); 10 11 // 註冊aliases 12 // Register aliases for bean name, if any. 13 String[] aliases = definitionHolder.getAliases(); 14 if (aliases != null) { 15 for (String alias : aliases) { 16 // 這裏調用的是SimpleAliasRegistry#registerAlias 17 registry.registerAlias(beanName, alias); 18 } 19 } 20 }
分析:測試
BeanDefinition註冊分兩步:
DefaultListableBeanFactory#registerBeanDefinition
1 public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) 2 throws BeanDefinitionStoreException { 3 // 校驗beanName與beanDefinition非空 4 Assert.hasText(beanName, "Bean name must not be empty"); 5 Assert.notNull(beanDefinition, "BeanDefinition must not be null"); 6 7 // 校驗BeanDefinition 8 // 這是註冊前的最後一次校驗,主要是對屬性methodOverrides進行校驗 9 if (beanDefinition instanceof AbstractBeanDefinition) { 10 try { 11 ((AbstractBeanDefinition) beanDefinition).validate(); 12 } catch (BeanDefinitionValidationException ex) { 13 throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, 14 "Validation of bean definition failed", ex); 15 } 16 } 17 // 從緩存中獲取指定beanName的BeanDefinition 18 BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); 19 // 若是緩存中存在 20 if (existingDefinition != null) { 21 // 若是存在可是不容許覆蓋,則拋出異常 22 if (!isAllowBeanDefinitionOverriding()) { 23 throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition); 24 } 25 // 覆蓋BeanDefinition的ROLE大於被覆蓋的ROLE,打印info日誌 26 else if (existingDefinition.getRole() < beanDefinition.getRole()) { 27 // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE 28 if (logger.isInfoEnabled()) { 29 logger.info("Overriding user-defined bean definition for bean '" + beanName + 30 "' with a framework-generated bean definition: replacing [" + 31 existingDefinition + "] with [" + beanDefinition + "]"); 32 } 33 } 34 // 若是覆蓋BeanDefinition與被覆蓋的BeanDefinition不相同,打印debug日誌 35 else if (!beanDefinition.equals(existingDefinition)) { 36 if (logger.isDebugEnabled()) { 37 logger.debug("Overriding bean definition for bean '" + beanName + 38 "' with a different definition: replacing [" + existingDefinition + 39 "] with [" + beanDefinition + "]"); 40 } 41 } 42 // 其餘,打印debug日誌 43 else { 44 if (logger.isTraceEnabled()) { 45 logger.trace("Overriding bean definition for bean '" + beanName + 46 "' with an equivalent definition: replacing [" + existingDefinition + 47 "] with [" + beanDefinition + "]"); 48 } 49 } 50 // 容許覆蓋,直接覆蓋原來的BeanDefinition 51 this.beanDefinitionMap.put(beanName, beanDefinition); 52 } 53 // 若是緩存中不存在 54 else { 55 // 檢測建立Bean階段是否已經開啓,若是開啓,須要對beanDefinitionMap作併發控制 56 if (hasBeanCreationStarted()) { 57 // beanDefinitionMap爲全局變量,避免併發狀況 58 // Cannot modify startup-time collection elements anymore (for stable iteration) 59 synchronized (this.beanDefinitionMap) { 60 // 添加BeanDefinition到beanDefinitionMap中 61 this.beanDefinitionMap.put(beanName, beanDefinition); 62 // 更新beanName集合beanDefinitionNames 63 List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1); 64 updatedDefinitions.addAll(this.beanDefinitionNames); 65 updatedDefinitions.add(beanName); 66 this.beanDefinitionNames = updatedDefinitions; 67 // 從manualSingletonNames中移除beanName 68 if (this.manualSingletonNames.contains(beanName)) { 69 Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames); 70 updatedSingletons.remove(beanName); 71 this.manualSingletonNames = updatedSingletons; 72 } 73 } 74 } 75 // 若是bean建立階段未開啓 76 else { 77 // Still in startup registration phase 78 // 添加BeanDefinition到beanDefinitionMap中 79 this.beanDefinitionMap.put(beanName, beanDefinition); 80 // 添加beanName到beanDefinitionNames集合中 81 this.beanDefinitionNames.add(beanName); 82 // 從manualSingletonNames中移除beanName 83 this.manualSingletonNames.remove(beanName); 84 } 85 this.frozenBeanDefinitionNames = null; 86 } 87 // 若是緩存存在,則更新beanName對應的緩存 88 if (existingDefinition != null || containsSingleton(beanName)) { 89 resetBeanDefinition(beanName); 90 } 91 }
分析:
整段函數理解起來仍是比較順暢的,這裏謹記咱們的最終落腳點beanDefinitionMap。
至此,BeanDefinition基於beanName和alias的維度,都已經注入到緩存中,接下來就是初始化而後使用bean了,接下來會繼續進行分析,這裏先看加載BeanDefinition的整個過程:
注:圖片來源芋道源碼
過多的總結顯得蒼白無力,最後一張圖片足以說明問題。
by Shawn Chen,2018.12.10日,晚。