Spring源码阅读-- IOC容器资源解析

上章节Spring源码阅读– IOC容器资源定位Spring IOC 容器在初始化时将配置的 Bean 定义资源文件定位封装成Resource对象。源文件的定位已分析完,接下来便是加载和解析配置文件。

回到AbstractBeanDefinitionReader类中的loadBeanDefinitions(String location, Set<Resource> actualResources)方法中

//代码片段1
public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
    ResourceLoader resourceLoader = getResourceLoader();
    if (resourceLoader == null) {
        throw new BeanDefinitionStoreException(
                "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
    }

    if (resourceLoader instanceof ResourcePatternResolver) {
        // Resource pattern matching available.
        try {
            //上一章讲解了将String类型的资源文件定位封装成Resource对象
            Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
            //现在开始加载资源文件,加载多个指定位置的 Bean 定义资源文件
            int loadCount = loadBeanDefinitions(resources);
            if (actualResources != null) {
                for (Resource resource : resources) {
                    actualResources.add(resource);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
            }
            return loadCount;
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException(
            "Could not resolve bean definition resource pattern [" + location + "]", ex);
        }
    }
    else {
        // Can only load single resources by absolute URL.
        Resource resource = resourceLoader.getResource(location);
        //加载单个指定位置的 Bean 定义资源文件,委派调用其子类 XmlBeanDefinitionReader 的方法, 实现加载功能
        int loadCount = loadBeanDefinitions(resource);
        if (actualResources != null) {
            actualResources.add(resource);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
        }
        return loadCount;
    }
}

//加载多个指定位置的 Bean 定义资源文件
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
    Assert.notNull(resources, "Resource array must not be null");
    int counter = 0;
    for (Resource resource : resources) {
        委派调用其子类 XmlBeanDefinitionReader 的方法, 实现加载每一个资源文件
        counter += loadBeanDefinitions(resource);
    }
    return counter;
}

由上面代码看出加载每一个资源文件的具体实现逻辑是委派给子类实现的。回到子类XmlBeanDefinitionReaderloadBeanDefinitions(Resource resource)方法中

//代码片段2
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
    //将读入的 XML 资源进行特殊编码处理
    return loadBeanDefinitions(new EncodedResource(resource));
}

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    Assert.notNull(encodedResource, "EncodedResource must not be null");
    if (logger.isInfoEnabled()) {
        logger.info("Loading XML bean definitions from " + encodedResource.getResource());
    }

    Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
    if (currentResources == null) {
        currentResources = new HashSet<EncodedResource>(4);
        this.resourcesCurrentlyBeingLoaded.set(currentResources);
    }
    if (!currentResources.add(encodedResource)) {
        throw new BeanDefinitionStoreException(
        "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
    }
    try {
        //将资源文件转为 InputStream 的 IO 流
        InputStream inputStream = encodedResource.getResource().getInputStream();
        try {
            //从 InputStream 中得到 XML 的解析源
            InputSource inputSource = new InputSource(inputStream);
            if (encodedResource.getEncoding() != null) {
                inputSource.setEncoding(encodedResource.getEncoding());
            }
            //这里是具体的读取过程
            return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
        }
        finally {
            //关闭从 Resource 中得到的 IO 流
            inputStream.close();
        }
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException(
        "IOException parsing XML document from " + encodedResource.getResource(), ex);
    }
    finally {
        currentResources.remove(encodedResource);
        if (currentResources.isEmpty()) {
            this.resourcesCurrentlyBeingLoaded.remove();
        }
    }
}

encodedResource.getResource().getInputStream();将配置文件转换成 IO流以后,InputSource inputSource = new InputSource(inputStream);传给InputSource对象,InputSource并不是Spring里的类,而是SAX中的,说明Spring解析XML用的是SAX的方式。

//代码片段3
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException {
    try {
        //将 XML 配置文件转换为 DOM 对象
        Document doc = doLoadDocument(inputSource, resource);
        //对 Bean 定义解析并完成注册
        return registerBeanDefinitions(doc, resource);
    }
    catch (BeanDefinitionStoreException ex) {
        throw ex;
    }
    catch (SAXParseException ex) {
        throw new XmlBeanDefinitionStoreException(resource.getDescription(),
                "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
    }
    catch (SAXException ex) {
        throw new XmlBeanDefinitionStoreException(resource.getDescription(),
                "XML document from " + resource + " is invalid", ex);
    }
    catch (ParserConfigurationException ex) {
        throw new BeanDefinitionStoreException(resource.getDescription(),
                "Parser configuration exception parsing XML from " + resource, ex);
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException(resource.getDescription(),
                "IOException parsing XML document from " + resource, ex);
    }
    catch (Throwable ex) {
        throw new BeanDefinitionStoreException(resource.getDescription(),
                "Unexpected exception parsing XML document from " + resource, ex);
    }
}

可见doLoadBeanDefinitions函数里完成两大功能:1、将 XML 配置文件转换为 DOM 对象;2、对 Bean 定义解析并完成注册到容器中

1、将 XML 配置文件转换为 DOM

使用配置的documentLoader完成将将配置文件的流解析成Document对象

//代码片段4
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
    //使用配置的documentLoader完成将将配置文件的流解析成Document对象
    return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
    getValidationModeForResource(resource), isNamespaceAware());
}

this.documentLoader在XmlBeanDefinitionReader实例化时就默认指定成DefaultDocumentLoader对象:private DocumentLoader documentLoader = new DefaultDocumentLoader();所以进入DefaultDocumentLoaderloadDocument方法:

//代码片段5
public Document loadDocument(InputSource inputSource,     EntityResolver entityResolver,
    ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
    //创建文件解析器工厂
    DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
    if (logger.isDebugEnabled()) {
    logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
    }
    //创建文档解析器
    DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
    //将配置文件的流解析成Document
    return builder.parse(inputSource);
}

该解析过程调用 JavaEE 标准的 JAXP 标准进行处理。至此 Spring IOC 容器根据定位的Bean定义资源文件,将其加载读入并转换成为 Document 对象过程完成。

2、对 Bean 定义解析

//代码片段6
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
    //创建BeanDefinitionDocumentReader 来对 xml 格式的 BeanDefinition 解析
    BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
    //获得容器中注册的 Bean 数量
    int countBefore = getRegistry().getBeanDefinitionCount();
    //解析过程入口
    documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
    return getRegistry().getBeanDefinitionCount() - countBefore;
}

createBeanDefinitionDocumentReader()函数默认创建DefaultBeanDefinitionDocumentReader对象来对 xml 格式的 BeanDefinition 解析,因此,进入DefaultBeanDefinitionDocumentReaderregisterBeanDefinitions方法:

//代码片段7
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
    this.readerContext = readerContext;
    logger.debug("Loading bean definitions");
    Element root = doc.getDocumentElement();
    doRegisterBeanDefinitions(root);
}
//代码片段8 
protected void doRegisterBeanDefinitions(Element root) {

    BeanDefinitionParserDelegate parent = this.delegate;
    //具体的解析过程由 BeanDefinitionParserDelegate 实现,
    //BeanDefinitionParserDelegate 中定义了 Spring Bean 定义 XML文件的各种元素
    this.delegate = createDelegate(getReaderContext(), root, parent);

    if (this.delegate.isDefaultNamespace(root)) {
        String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
        if (StringUtils.hasText(profileSpec)) {
            String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
            if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
                if (logger.isInfoEnabled()) {
                    logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
                            "] not matching: " + getReaderContext().getResource());
                }
                return;
            }
        }
    }
    //在解析 Bean 定义之前, 进行自定义的解析, 增强解析过程的可扩展性
    preProcessXml(root);
    //从 Document 的根元素开始进行 Bean 定义的 Document 对象
    parseBeanDefinitions(root, this.delegate);
    //在解析 Bean 定义之后, 进行自定义的解析, 增加解析过程的可扩展性
    postProcessXml(root);

    this.delegate = parent;
}
//创建 BeanDefinitionParserDelegate, 用于完成真正的解析过程
protected BeanDefinitionParserDelegate createDelegate(
    XmlReaderContext readerContext, Element root, BeanDefinitionParserDelegate parentDelegate) {

    BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
    //BeanDefinitionParserDelegate 初始化 Document 根元素
    delegate.initDefaults(root, parentDelegate);
    return delegate;
}

进入parseBeanDefinitions方法。

//代码片段9
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    // 检查root节点的命名空间是否为默认命名空间
    // spring配置文件中默认的命名空间为"http://www.springframework.org/schema/beans"
    if (delegate.isDefaultNamespace(root)) {
        NodeList nl = root.getChildNodes();
         // 遍历root节点下的所有子节点
        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 {
                    //没有使用 Spring 默认的 XML 命名空间, 则使用用户自定义的解析规则解析元素节点
                    delegate.parseCustomElement(ele);
                }
            }
        }
    }
    else {
        //Document 的根节点没有使用 Spring 默认的命名空间, 则使用用户自定义的
        delegate.parseCustomElement(root);
    }
}

parseBeanDefinitions方法的主要事情是区分节点标签是否是默认命名空间的标签。如果是默认命名空间的则调用DefaultBeanDefinitionDocumentReader方法parseDefaultElement处理,否则调用BeanDefinitionParserDelegate 的parseCustomElement方法来处解析自定义命名空间的标签。

下面我们先看看默认命名空间的元素节点的解析过程

//代码片段10
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
    if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
        //处理<import>节点元素
        importBeanDefinitionResource(ele);
    }
    else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
        // 处理<alias>节点元素
        processAliasRegistration(ele);
    }
    else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
        //处理<bean>节点元素
        processBeanDefinition(ele, delegate);
    }
    else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
        //处理<beans>节点元素,递归调用doRegisterBeanDefinitions,见"代码片段8"
        doRegisterBeanDefinitions(ele);
    }
}

2.1、处理节点元素

在Spring的配置文件,有时候为了分模块的更加清晰的进行相关实体类的配置,通常使用import标签是引入其它spring配置文件,如:

<import resource="classpath*:/spring/job-timer.xml" />

解析节点元素代码如下:

protected void importBeanDefinitionResource(Element ele) {
    //获取<import>的 resource 属性值,如classpath*:/spring/job-timer.xml
    String location = ele.getAttribute(RESOURCE_ATTRIBUTE);//RESOURCE_ATTRIBUTE = "resource"
    if (!StringUtils.hasText(location)) {
        //如果导入元素的 resource 属性值为空, 则没有导入任何资源, 直接返回
        getReaderContext().error("Resource location must not be empty", ele);
        return;
    }

    // Resolve system properties: e.g. "${user.dir}"
    //使用系统变量值解析 location 属性值,就是把如"${user.dir}"这样的系统变量替换成变量的实际值
    location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);

    Set<Resource> actualResources = new LinkedHashSet<Resource>(4);

    // Discover whether the location is an absolute or relative URI
    boolean absoluteLocation = false;
    try {
        absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
    }
    catch (URISyntaxException ex) {
    // cannot convert to an URI, considering the location relative
    // unless it is the well-known Spring prefix "classpath*:"
    }

    // Absolute or relative?
    if (absoluteLocation) {//给定的导入元素的 location 是绝对路径
        try {
            //使用资源读入器加载给定路径的 Bean 定义资源
            int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
            if (logger.isDebugEnabled()) {
                logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
            }
        }
        catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to import bean definitions from URL location [" + location + "]", ele, ex);
        }
    }
    else {
        // No URL -> considering resource location as relative to the current file.
        try {
                int importCount;
                //将给定导入元素的 location 封装为相对路径资源
                Resource relativeResource = getReaderContext().getResource().createRelative(location);
                if (relativeResource.exists()) {
                    importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
                    actualResources.add(relativeResource);
                }
                else {
                    String baseLocation = getReaderContext().getResource().getURL().toString();
                    importCount = getReaderContext().getReader().loadBeanDefinitions(
                    StringUtils.applyRelativePath(baseLocation, location), actualResources);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
                }
        }
        catch (IOException ex) {
            getReaderContext().error("Failed to resolve current resource location", ele, ex);
        }
        catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",ele, ex);
        }
    }
    Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
    //在解析完<import>元素之后, 发送容器<import>处理完成事件
    getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}

上面代码可以看出,如果的 resource属性指定的路径是绝对路径则使用getReaderContext().getReader().loadBeanDefinitions(location, actualResources)加载导入的bean配置文件,getReaderContext().getReader()得到就是XmlBeanDefinitionReader对象,loadBeanDefinitions(location, actualResources)调用的函数就是在XmlBeanDefinitionReader的父类AbstractBeanDefinitionReader中实现。AbstractBeanDefinitionReader的方法loadBeanDefinitions(String location, Set<Resource> actualResources) Spring源码阅读– IOC容器资源定位 中”代码片段11”讲解过了。
如果的 resource属性指定的路径是相对路径则使用getReaderContext().getReader().loadBeanDefinitions(relativeResource)XmlBeanDefinitionReaderloadBeanDefinitions(Resource resource)方法处理,此方法在本文前面的”代码片段2”也讲解过了。

2.2、处理节点元素

在对bean进行定义时,除了使用id属性来指定名称之外,为了提供多个名称,可以使用alias标签来指定,。而所有的这些名称都指向同一个bean。如:

<bean id="zhangsan"  class="com.igood.entity.User"/>
<!--给zhangsan这个bean起几个别名,其中有一个别名和原来bean名称相同-->
<alias name="zhangsan" alias="zhangsan,zhang3,alias1"/>

解析节点元素代码如下:

protected void processAliasRegistration(Element ele) {
    //获取<alias>别名节点元素中 name 的属性值
    String name = ele.getAttribute(NAME_ATTRIBUTE);// NAME_ATTRIBUTE = "name"
    //获取<alias>别名节点元素中 alias 的属性值
    String alias = ele.getAttribute(ALIAS_ATTRIBUTE);//ALIAS_ATTRIBUTE = "alias"
    boolean valid = true;
    if (!StringUtils.hasText(name)) {
        //name 属性值为空
        getReaderContext().error("Name must not be empty", ele);
        valid = false;
    }
    if (!StringUtils.hasText(alias)) {
        //alias 属性值为空
        getReaderContext().error("Alias must not be empty", ele);
        valid = false;
    }
    if (valid) {
        try {
            getReaderContext().getRegistry().registerAlias(name, alias);
        }
        catch (Exception ex) {
            getReaderContext().error("Failed to register alias '" + alias +
                "' for bean with name '" + name + "'", ele, ex);
        }
        getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
    }
}
2.2.1、分析别名注册中心

上面的代码从getReaderContext()中取得的registry就是spring注册bean定义的注册中心,所有的bean都要注册到这个注册中心去。这个registry到底是什么东西呢,这要要从XmlBeanDefinitionReader的创建说起,再回顾下上一篇文章 Spring源码阅读–IOC容器资源定位中”代码片段8”:

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    // Create a new XmlBeanDefinitionReader for the given BeanFactory.
    //创建一个XmlBeanDefinitionReader类型的对象读取Xml配置文件
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

    // Configure the bean definition reader with this context's
    // resource loading environment.
    beanDefinitionReader.setEnvironment(this.getEnvironment());
    //设置资源加载器就是容器本身
    beanDefinitionReader.setResourceLoader(this);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

    // Allow a subclass to provide custom initialization of the reader,
    // then proceed with actually loading the bean definitions.
    initBeanDefinitionReader(beanDefinitionReader);
    loadBeanDefinitions(beanDefinitionReader);
}

创建XmlBeanDefinitionReader的时候传入的了一个DefaultListableBeanFactory类型的beanFactory。这个beanFactory其实就是刚刚提到的注册中心registry。XmlBeanDefinitionReader的构造函数如下:

public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
    super(registry);
}

XmlBeanDefinitionReader构造函数直接调用父AbstractBeanDefinitionReader类的构造方法

protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
    this.registry = registry;
    //省略其他代码
}

然后XmlBeanDefinitionReadercreateReaderContext方法中又将自己(this)传给了ReaderContext。

public XmlReaderContext createReaderContext(Resource resource) {
    return new XmlReaderContext(resource, this.problemReporter, this.eventListener,
            this.sourceExtractor, this, getNamespaceHandlerResolver());
}

因此,解析节点元素代码processAliasRegistration方法中调用getReaderContext().getRegistry()获得到的registry就是DefaultListableBeanFactory对象

2.2.2、注册bean别名

先看DefaultListableBeanFactory类的继承关系图
image
可见DefaultListableBeanFactory继承了SimpleAliasRegistryDefaultListableBeanFactory并没有覆盖registerAlias(String name, String alias)方法。因此注册bean别名的具体实现逻辑就在SimpleAliasRegistry类中。

public void registerAlias(String name, String alias) {
    Assert.hasText(name, "'name' must not be empty");
    Assert.hasText(alias, "'alias' must not be empty");
    if (alias.equals(name)) {
        //别名和bean名称相同,则删除该别名(不使用该别名,直接当做bean名称使用)
        this.aliasMap.remove(alias);
    }
    else {
        String registeredName = this.aliasMap.get(alias);
        if (registeredName != null) {
            if (registeredName.equals(name)) {
                // An existing alias - no need to re-register
                return;
            }
            if (!allowAliasOverriding()) {
                throw new IllegalStateException("Cannot register alias '" + alias + "' for name '" + name + "': It is already registered for name '" + registeredName + "'.");
            }
        }
        //检查别名和bean名称是否有循环引用
        checkForAliasCircle(name, alias);
        /如果有别名,以别名为key值,name为value值,保存到一个map中
        this.aliasMap.put(alias, name);
    }
}

aliasMap在在SimpleAliasRegistry类中定义如下

private final Map<String, String> aliasMap = new ConcurrentHashMap<String, String>(16);

这里可以看出,封装alias标签,其实就是把别名和name放到一个map中,建立对应关系。

2.3、处理节点元素

解析bean标签,调用的processBeanDefinition()方法

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    // BeanDefinitionHolder 是对 BeanDefinition 的封装, 即 Bean 定义的封装类
    //对 Document 对象中<bean> 元素的解析由 BeanDefinitionParserDelegate 实现 BeanDefinitionHolder
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        //对BeanDefinition对象再加工,主要是解析bean标签中自定义属性和自定义标签
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            //向 Spring IoC 容器注册解析得到的 Bean 定义, 这是 Bean 定义向 IOC 容器注册的入口
            BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
        }
        catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to register bean definition with name '" +
                    bdHolder.getBeanName() + "'", ele, ex);
        }
         // 发送BeanDefinition 注册完成事件
        getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }
}
2.3.1、解析节点元素

进入到BeanDefinitionParserDelegate类的parseBeanDefinitionElement方法中

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
    String id = ele.getAttribute(ID_ATTRIBUTE);// 获取id属性值
    String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);// 获取name属性值

    List<String> aliases = new ArrayList<String>();
    if (StringUtils.hasLength(nameAttr)) {
        //将<bean>元素中的所有 name 属性值存放到别名中
        String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, ",; ");
        aliases.addAll(Arrays.asList(nameArr));
    }

    String beanName = id;
    if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
        // 没有定义bean的名称,就使用第一个alias作为id
        beanName = aliases.remove(0);
        if (logger.isDebugEnabled()) {
            logger.debug("No XML 'id' specified - using '" + beanName +
                    "' as bean name and " + aliases + " as aliases");
        }
    }

    if (containingBean == null) {
        // 检查id和别名是否已经被使用了,如果已经被其他bean占用,则会抛出异常
        checkNameUniqueness(beanName, aliases, ele);
    }
    // 详细对<bean> 元素中配置的bean 定义进行解析的地方
    AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
    if (beanDefinition != null) {
        if (!StringUtils.hasText(beanName)) {
            try {
                if (containingBean != null) {
                    //如果<bean>元素中没有配置 id、 别名或者 name, 且没有包含子元素
                    //<bean>元素, 为解析的 Bean 生成一个唯一 beanName 并注册
                    beanName = BeanDefinitionReaderUtils.generateBeanName(
                            beanDefinition, this.readerContext.getRegistry(), true);
                }
                else {
                    beanName = this.readerContext.generateBeanName(beanDefinition);
                    //为解析的 Bean 使用别名注册时,为了向后兼容,Spring1.2/2.0, 给别名添加类名后缀
                    String beanClassName = beanDefinition.getBeanClassName();
                    if (beanClassName != null &&
                            beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
                            !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
                        aliases.add(beanClassName);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" + beanName + "]");
                }
            }
            catch (Exception ex) {
                error(ex.getMessage(), ele);
                return null;
            }
        }
        String[] aliasesArray = StringUtils.toStringArray(aliases);
        return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
    }
    //当解析出错时, 返回 null
    return null;
}

上面的方法中已经对Bean 的 id、 name 和别名等属性进行了处理, 而Bean 的 其他属性,如class,parent,lazy-init等属性放在parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean)方法中处理

public AbstractBeanDefinition parseBeanDefinitionElement(
    Element ele, String beanName, BeanDefinition containingBean) {

    this.parseState.push(new BeanEntry(beanName));

    String className = null;
    if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
        //获取class属性值
        className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
    }

    try {
        String parent = null;
        if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
            //获取parent属性值
            parent = ele.getAttribute(PARENT_ATTRIBUTE);
        }
        /
        /根据<Bean>元素配置的 class 名称和 parent 属性值创建 BeanDefinition
        //为载入 Bean 定义信息做准备
        AbstractBeanDefinition bd = createBeanDefinition(className, parent);
        //对当前的<Bean>元素中配置的一些属性进行解析和设置, 如配置的单态(singleton)属性等
        parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
        //为<Bean>元素解析的 Bean 设置 description 信息
        bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
        //对<Bean>元素的 meta(元信息)属性解析
        parseMetaElements(ele, bd);
        //对<Bean>元素的 lookup-method 属性解析
        parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
        //对<Bean>元素的 replaced-method 属性解析
        parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
        //解析<Bean>元素的构造方法设置
        parseConstructorArgElements(ele, bd);
        //解析<Bean>元素的<property>设置
        parsePropertyElements(ele, bd);
        //解析<Bean>元素的 qualifier 属性
        parseQualifierElements(ele, bd);
        //为当前解析的 Bean 设置所需的资源和依赖对象
        bd.setResource(this.readerContext.getResource());
        bd.setSource(extractSource(ele));

        return bd;
    }
    catch (ClassNotFoundException ex) {
        error("Bean class [" + className + "] not found", ele, ex);
    }
    catch (NoClassDefFoundError err) {
        error("Class that bean class [" + className + "] depends on not found", ele, err);
    }
    catch (Throwable ex) {
        error("Unexpected failure during bean definition parsing", ele, ex);
    }
    finally {
        this.parseState.pop();
    }

    return null;
}

上面方法中对一些配置如元信息(meta)、 lookup-method、replaced-method 、property、qualifier 等属性进行解析,最终将元素中的配置信息设置到BeanDefinition对象中,BeanDefinition中保存是创建bean的原材料。由于篇幅原因,这些属性的解析就不分析了。

3、总结

XmlBeanDefinitionReader类执行对Resource类型的BeanDefinition对象加载任务后,将资源文件转为 InputStream 的 IO 流,然后使用DocumentLoader的实现类DefaultDocumentLoader来将配置文件的流解析成Document对象。接着,使用DefaultBeanDefinitionDocumentReader来操作Document对象,把Document对象中包含的配置信息转换成BeanDefinition对象。
同样画出本文件的代码执行简要过程图
image

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值