public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// Prepare this context for refreshing.prepareRefresh();// Tell the subclass to refresh the internal bean factory.//這里是在子類中啟動refreshBeanFactory()的地方,也就是創建實際BeanFactory的方法入口ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.prepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses.//設置BeanFactory的后置處理postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.//調用BeanFactory的后處理器.這些后處理器是在Bean定義中向容器注冊的invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.//注冊Bean的后處理器,在Bean創建過程中調用。registerBeanPostProcessors(beanFactory);// Initialize message source for this context.、//對上下文中的消息源進行初始化initMessageSource();// Initialize event multicaster for this context.//初始化上下文中的事件機制initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.//初始化其他的特殊BeanonRefresh();// Check for listener beans and register them.//檢查監聽Bean并且將這些Bean向容器注冊registerListeners();// Instantiate all remaining (non-lazy-init) singletons.//實例化所有的(non-lazy-init)單件finishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event.//發布容器事件.結束Refresh過程finishRefresh();}catch (BeansException ex) {// Destroy already created singletons to avoid dangling resources.//為防止Bean資源占用,在異常處理中,銷毀已經在前面過程中生成的單間BeandestroyBeans();// Reset 'active' flag.cancelRefresh(ex);// Propagate exception to caller.throw ex;}}}
//DefaultBeanDefinitionDocumentReader中的registerBeanDefinitions方法
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {//將封裝了XmlBeanDefinitionReader等組件的XmlReaderContext傳給DefaultBeanDefinitionDocumentReader,方便后續回調。this.readerContext = readerContext;logger.debug("Loading bean definitions");Element root = doc.getDocumentElement();doRegisterBeanDefinitions(root);
}//DefaultBeanDefinitionDocumentReader中的doRegisterBeanDefinitions方法
protected void doRegisterBeanDefinitions(Element root) {String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);if (StringUtils.hasText(profileSpec)) {Assert.state(this.environment != null, "environment property must not be null");String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);if (!this.environment.acceptsProfiles(specifiedProfiles)) {return;}}// any nested <beans> elements will cause recursion in this method. In// order to propagate and preserve <beans> default-* attributes correctly,// keep track of the current (parent) delegate, which may be null. Create// the new (child) delegate with a reference to the parent for fallback purposes,// then ultimately reset this.delegate back to its original (parent) reference.// this behavior emulates a stack of delegates without actually necessitating one.//對文檔進行解析的實際作用類BeanDefinitionParserDelegateBeanDefinitionParserDelegate parent = this.delegate;this.delegate = createHelper(readerContext, root, parent);preProcessXml(root);//利用BeanDefinitionParserDelegate進行解析的入口方法parseBeanDefinitions(root, this.delegate);postProcessXml(root);this.delegate = parent;
}//DefaultBeanDefinitionDocumentReader中的parseBeanDefinitions方法
//遍歷子節點,也就是XML文件中的標簽,依次解析
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {if (delegate.isDefaultNamespace(root)) {NodeList nl = root.getChildNodes();for (int i = 0; i < nl.getLength(); i++) {Node node = nl.item(i);if (node instanceof Element) {Element ele = (Element) node;if (delegate.isDefaultNamespace(ele)) {parseDefaultElement(ele, delegate);}else {delegate.parseCustomElement(ele);}}}}else {delegate.parseCustomElement(root);}
}//DefaultBeanDefinitionDocumentReader中的parseDefaultElement方法
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {//對"import"標簽進行處理if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {importBeanDefinitionResource(ele);}//對"alias"標簽進行處理else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {processAliasRegistration(ele);}//對"bean"標簽進行處理,是主要的解析標簽。else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {processBeanDefinition(ele, delegate);}//對"beans"標簽進行處理else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {// recursedoRegisterBeanDefinitions(ele);}
}//DefaultBeanDefinitionDocumentReader中的processBeanDefinition方法
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {//由BeanDefinitionParserDelegate負責解析,BeanDefinitionHolder是BeanDefinition的//封裝類,用于完成向IoC容器的注冊BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);if (bdHolder != null) {bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);try {// Register the final decorated instance.//載入解析完,注冊的入口函數BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());}catch (BeanDefinitionStoreException ex) {getReaderContext().error("Failed to register bean definition with name '" +bdHolder.getBeanName() + "'", ele, ex);}// Send registration event.getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));}
}
//BeanDefinitionParserDelegate中的parsePropertySubElement方法,對property的子標簽進行解析
public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultValueType) {if (!isDefaultNamespace(ele)) {return parseNestedCustomElement(ele, bd);}//子標簽為bean的解析else if (nodeNameEquals(ele, BEAN_ELEMENT)) {BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);if (nestedBd != null) {nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);}return nestedBd;}//子標簽為ref的解析else if (nodeNameEquals(ele, REF_ELEMENT)) {// A generic reference to any name of any bean.String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);boolean toParent = false;if (!StringUtils.hasLength(refName)) {// A reference to the id of another bean in the same XML file.refName = ele.getAttribute(LOCAL_REF_ATTRIBUTE);if (!StringUtils.hasLength(refName)) {// A reference to the id of another bean in a parent context.refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);toParent = true;if (!StringUtils.hasLength(refName)) {error("'bean', 'local' or 'parent' is required for <ref> element", ele);return null;}}}if (!StringUtils.hasText(refName)) {error("<ref> element contains empty target attribute", ele);return null;}RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);ref.setSource(extractSource(ele));return ref;}//子標簽為idref的解析else if (nodeNameEquals(ele, IDREF_ELEMENT)) {return parseIdRefElement(ele);}//子標簽為value的解析else if (nodeNameEquals(ele, VALUE_ELEMENT)) {return parseValueElement(ele, defaultValueType);}else if (nodeNameEquals(ele, NULL_ELEMENT)) {// It's a distinguished null value. Let's wrap it in a TypedStringValue// object in order to preserve the source location.TypedStringValue nullHolder = new TypedStringValue(null);nullHolder.setSource(extractSource(ele));return nullHolder;}//子標簽為array的解析else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {return parseArrayElement(ele, bd);}//子標簽為list的解析else if (nodeNameEquals(ele, LIST_ELEMENT)) {return parseListElement(ele, bd);}//子標簽為set的解析else if (nodeNameEquals(ele, SET_ELEMENT)) {return parseSetElement(ele, bd);}//子標簽為map的解析else if (nodeNameEquals(ele, MAP_ELEMENT)) {return parseMapElement(ele, bd);}else if (nodeNameEquals(ele, PROPS_ELEMENT)) {return parsePropsElement(ele);}else {error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);return null;}}//BeanDefinitionParserDelegate中的parseListElement方法,解析list標簽,將解析結果封裝在ManagedList中。
public List parseListElement(Element collectionEle, BeanDefinition bd) {String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);NodeList nl = collectionEle.getChildNodes();ManagedList<Object> target = new ManagedList<Object>(nl.getLength());target.setSource(extractSource(collectionEle));target.setElementTypeName(defaultElementType);target.setMergeEnabled(parseMergeAttribute(collectionEle));//開始解析list下的標簽parseCollectionElements(nl, target, bd, defaultElementType);return target;}protected void parseCollectionElements(NodeList elementNodes, Collection<Object> target, BeanDefinition bd, String defaultElementType) {for (int i = 0; i < elementNodes.getLength(); i++) {Node node = elementNodes.item(i);if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {//加入到target中,target是一個ManagedList,同時開始對下一層子元素的解析過程。是一個遞歸調用。target.add(parsePropertySubElement((Element) node, bd, defaultElementType));}}}