Spring源码(一)

Spring配置文件读取:

使用Resource接口的各种实现类(classPathResource、FileSystemResource等)将spring配置文件转化为Resource对象;

Resource resource = new ClassPathResource("spring-config.xml");

通过DocumentLoader对象或其实现类(XmlDocumentLoader等)将Reource对象转换为Document对象;

Document doc = this.doLoadDocument(inputSource, resource);
==>
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
    return this.documentLoader.loadDocument(inputSource, this.getEntityResolver(), this.errorHandler, this.getValidationModeForResource(resource), this.isNamespaceAware());
}
==>
// EntityResolver用于指定本地XML DTD约束文件位置
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
    DocumentBuilderFactory factory = this.createDocumentBuilderFactory(validationMode, namespaceAware);
    if (logger.isDebugEnabled()) {
        logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
    }

    DocumentBuilder builder = this.createDocumentBuilder(factory, entityResolver, errorHandler);
    return builder.parse(inputSource);
}
==>
public Document parse(InputSource is) throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException(
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN,
            "jaxp-null-input-source", null));
    }
    if (fSchemaValidator != null) {
        if (fSchemaValidationManager != null) {
            fSchemaValidationManager.reset();
            fUnparsedEntityHandler.reset();
        }
        resetSchemaValidator();
    }
    domParser.parse(is);
    Document doc = domParser.getDocument();
    domParser.dropDocumentReferences();
    return doc;
}

创建BeanDefinitionDocumentReader对象,通过其BeanDefinitionParserDelegate属性解析Document对象,实现Bean的注册:

在这里插入图片描述
在这里插入图片描述
对于Element命名空间的判断用于断定是对默认的bean申明还是自定义的bean申明进行解析。
在这里插入图片描述


默认标签的解析(import、alisa、bean、beans):

bean标签的解析:

(1)解析bean标签默认属性:BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);

1)解析id、name属性
	String id = ele.getAttribute("id");
	String nameAttr = ele.getAttribute("name");
	List<String> aliases = new ArrayList();
	if (StringUtils.hasLength(nameAttr)) {
	    String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, ",; ");
	    aliases.addAll(Arrays.asList(nameArr));
	}
	// 设置beanName:如果id存在则为id,如果不存在则取name数组的第一项
	String beanName = id;
	if (!StringUtils.hasText(id) && !aliases.isEmpty()) {
	    beanName = (String)aliases.remove(0);
	    if (this.logger.isDebugEnabled()) {
	        this.logger.debug("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases");
	    }
	}2)解析其他属性,封装至GenericBeanDefinition:
	AbstractBeanDefinition beanDefinition = this.parseBeanDefinitionElement(ele, beanName, containingBean);
	...
	public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean) {
     this.parseState.push(new BeanEntry(beanName));
     String className = null;
     if (ele.hasAttribute("class")) {
         className = ele.getAttribute("class").trim();
     }

     try {
         String parent = null;
         if (ele.hasAttribute("parent")) {
             parent = ele.getAttribute("parent");
         }
		
         AbstractBeanDefinition bd = this.createBeanDefinition(className, parent);
         // 对element所有属性(scope、autowired、init-method等)进行解析,封装至bd
         this.parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
         bd.setDescription(DomUtils.getChildElementValueByTagName(ele, "description"));
         this.parseMetaElements(ele, bd);
         // 获取器注入
         this.parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
         // 运行期方法替换
         this.parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
         // 解析构造参数(<constructor-arg name="argName" value="argValue"/>)
         this.parseConstructorArgElements(ele, bd);
         // 解析property参数()
         this.parsePropertyElements(ele, bd);
         this.parseQualifierElements(ele, bd);
         bd.setResource(this.readerContext.getResource());
         bd.setSource(this.extractSource(ele));
         AbstractBeanDefinition var7 = bd;
         return var7;
     } catch (ClassNotFoundException var13) {
     ...
}

(2)解析bean标签自定义属性:bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);

 public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) {
    BeanDefinitionHolder finalDefinition = definitionHolder;
    NamedNodeMap attributes = ele.getAttributes();
	// 判断是否有自定义属性
    for(int i = 0; i < attributes.getLength(); ++i) {
        Node node = attributes.item(i);
        finalDefinition = this.decorateIfRequired(node, finalDefinition, containingBd);
    }

    NodeList children = ele.getChildNodes();
	// 判断是否有自定义子节点
    for(int i = 0; i < children.getLength(); ++i) {
        Node node = children.item(i);
        if (node.getNodeType() == 1) {
            finalDefinition = this.decorateIfRequired(node, finalDefinition, containingBd);
        }
    }

    return finalDefinition;
}
public BeanDefinitionHolder decorateIfRequired(Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd) {
    String namespaceUri = this.getNamespaceURI(node);
    if (!this.isDefaultNamespace(namespaceUri)) {
        NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
        if (handler != null) {
            return handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd));
        }

        if (namespaceUri != null && namespaceUri.startsWith("http://www.springframework.org/")) {
            this.error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node);
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]");
        }
    }

    return originalDef;
}

(3)注册解析的BeanDefinition:BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, this.getReaderContext().getRegistry());

(1)根据beanName进行注册:
   public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
       ...
       // 校验beanDefinition
       if (beanDefinition instanceof AbstractBeanDefinition) {
           try {
               ((AbstractBeanDefinition)beanDefinition).validate();
           } catch (BeanDefinitionValidationException var9) {
               throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", var9);
           }
       }
	   // 处理beanName已经注册过的情况
       BeanDefinition oldBeanDefinition = (BeanDefinition)this.beanDefinitionMap.get(beanName);
       if (oldBeanDefinition != null) {
           if (!this.isAllowBeanDefinitionOverriding()) {
               throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName + "': There is already [" + oldBeanDefinition + "] bound.");
           }

           if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
               if (this.logger.isWarnEnabled()) {
                   this.logger.warn("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
               }
           } else if (!beanDefinition.equals(oldBeanDefinition)) {
               if (this.logger.isInfoEnabled()) {
                   this.logger.info("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
               }
           } else if (this.logger.isDebugEnabled()) {
               this.logger.debug("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
           }

           this.beanDefinitionMap.put(beanName, beanDefinition);
       } else {
       	   // 判断是否已经有bean被创建
           if (this.hasBeanCreationStarted()) {
               synchronized(this.beanDefinitionMap) {
                   this.beanDefinitionMap.put(beanName, beanDefinition);
                   List<String> updatedDefinitions = new ArrayList(this.beanDefinitionNames.size() + 1);
                   // 避免beanDefinitionNames遍历是出现fail-fast	
                   updatedDefinitions.addAll(this.beanDefinitionNames);
                   updatedDefinitions.add(beanName);
                   this.beanDefinitionNames = updatedDefinitions;
                   // 判断手动注入的单例bean中是否包含当前beanName对应的bean
                   if (this.manualSingletonNames.contains(beanName)) {
                       Set<String> updatedSingletons = new LinkedHashSet(this.manualSingletonNames);
                       updatedSingletons.remove(beanName);
                       this.manualSingletonNames = updatedSingletons;
                   }
               }
           } else {
               this.beanDefinitionMap.put(beanName, beanDefinition);
               this.beanDefinitionNames.add(beanName);
               this.manualSingletonNames.remove(beanName);
           }

           this.frozenBeanDefinitionNames = null;
       }

       if (oldBeanDefinition != null || this.containsSingleton(beanName)) {
           this.resetBeanDefinition(beanName);
       }

   }
(2)通过别名注册beanDefinition:
	public void registerAlias(String name, String alias) {
        Assert.hasText(name, "'name' must not be empty");
        Assert.hasText(alias, "'alias' must not be empty");
        synchronized(this.aliasMap) {
            if (alias.equals(name)) {
                this.aliasMap.remove(alias);
            } else {
                String registeredName = (String)this.aliasMap.get(alias);
                if (registeredName != null) {
                    if (registeredName.equals(name)) {
                        return;
                    }

                    if (!this.allowAliasOverriding()) {
                        throw new IllegalStateException("Cannot register alias '" + alias + "' for name '" + name + "': It is already registered for name '" + registeredName + "'.");
                    }
                }
				// alisa循环检查
                this.checkForAliasCircle(name, alias);
                this.aliasMap.put(alias, name);
            }

        }
    }

(4)通知监听器解析及注册完成:this.getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));

// 暂无实现
public void fireComponentRegistered(ComponentDefinition componentDefinition) {
    this.eventListener.componentRegistered(componentDefinition);
}
alias标签的解析:
protected void processAliasRegistration(Element ele) {
    String name = ele.getAttribute("name");
    String alias = ele.getAttribute("alias");
    boolean valid = true;
    if (!StringUtils.hasText(name)) {
        this.getReaderContext().error("Name must not be empty", ele);
        valid = false;
    }

    if (!StringUtils.hasText(alias)) {
        this.getReaderContext().error("Alias must not be empty", ele);
        valid = false;
    }

    if (valid) {
        try {
        	// 根据别名注册bean与上节中的根据alias注册bean完全一致
            this.getReaderContext().getRegistry().registerAlias(name, alias);
        } catch (Exception var6) {
            this.getReaderContext().error("Failed to register alias '" + alias + "' for bean with name '" + name + "'", ele, var6);
        }

        this.getReaderContext().fireAliasRegistered(name, alias, this.extractSource(ele));
    }

}
import标签的解析:

根据import标签的resource属性解析为对应的Resource对象,递归调用执行bean注册。

protected void importBeanDefinitionResource(Element ele) {
	// 解析import标签的resource属性
    String location = ele.getAttribute("resource");
    if (!StringUtils.hasText(location)) {
        this.getReaderContext().error("Resource location must not be empty", ele);
    } else {
    	// 解析location中的系统属性
        location = this.getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
        Set<Resource> actualResources = new LinkedHashSet(4);
        boolean absoluteLocation = false;

        try {
        	// 判断引入资源路径是绝对路径还是相对路径
            absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
        } catch (URISyntaxException var11) {
        }

        int importCount;
        // 如果是绝对路径直接调用loadBeanDefinitions进行加载
        if (absoluteLocation) {
            try {
                importCount = this.getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
                }
            } catch (BeanDefinitionStoreException var10) {
                this.getReaderContext().error("Failed to import bean definitions from URL location [" + location + "]", ele, var10);
            }
        } else {
        	// 如果是相对路径则根据相对路径获取绝对路径
            try {
                Resource relativeResource = this.getReaderContext().getResource().createRelative(location);
                if (relativeResource.exists()) {
                    importCount = this.getReaderContext().getReader().loadBeanDefinitions(relativeResource);
                    actualResources.add(relativeResource);
                } else {
                    String baseLocation = this.getReaderContext().getResource().getURL().toString();
                    importCount = this.getReaderContext().getReader().loadBeanDefinitions(StringUtils.applyRelativePath(baseLocation, location), actualResources);
                }

                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
                }
            } catch (IOException var8) {
                this.getReaderContext().error("Failed to resolve current resource location", ele, var8);
            } catch (BeanDefinitionStoreException var9) {
                this.getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]", ele, var9);
            }
        }

        Resource[] actResArray = (Resource[])actualResources.toArray(new Resource[actualResources.size()]);
        this.getReaderContext().fireImportProcessed(location, actResArray, this.extractSource(ele));
    }
beans标签的解析:

beans标签的解析与加载与import标签类似,递归调用beans的解析过程。


总结:Spring配置文件的加载过程就是对Spring配置文件中各种标签的解析过程,最终将对bean标签的解析结果封装为BeanDefinition添加至beanDefinitionMap中,key为beanName,后序实例化bean时就根据beanDefinition执行bean的实例化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值