Spring5源碼分析(二) IOC 容器的初始化(三)

  承接上一篇文章繼續分析FileSystemXmlApplicationContextIOC容器建立的流程。java

2.10 DefaultBeanDefinitionDocumentReader對Bean定義的Document對象解析

BeanDefinitionDocumentReader 接 口 通 過 registerBeanDefinitions 方 法調用其實現類DefaultBeanDefinitionDocumentReader對Document對象進行解析,解析的代碼以下:node

//根據Spring DTD對Bean的定義規則解析Bean定義Document對象
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
    //得到XML描述符
    this.readerContext = readerContext;
    logger.debug("Loading bean definitions");
    //得到Document的根元素
    Element root = doc.getDocumentElement();
    doRegisterBeanDefinitions(root);
}

protected void doRegisterBeanDefinitions(Element root) {

    //具體的解析過程由BeanDefinitionParserDelegate實現,
    //BeanDefinitionParserDelegate中定義了Spring Bean定義XML文件的各類元素
    BeanDefinitionParserDelegate parent = this.delegate;
    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, @Nullable BeanDefinitionParserDelegate parentDelegate) {

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

//使用Spring的Bean規則從Document的根元素開始進行Bean定義的Document對象
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    //Bean定義的Document對象使用了Spring默認的XML命名空間
    if (delegate.isDefaultNamespace(root)) {
        //獲取Bean定義的Document對象根元素的全部子節點
        NodeList nl = root.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            //得到Document節點是XML元素節點
            if (node instanceof Element) {
                Element ele = (Element) node;
                //Bean定義的Document的元素節點使用的是Spring默認的XML命名空間
                if (delegate.isDefaultNamespace(ele)) {
                    //使用Spring的Bean規則解析元素節點
                    parseDefaultElement(ele, delegate);
                }
                else {
                    //沒有使用Spring默認的XML命名空間,則使用用戶自定義的解//析規則解析元素節點
                    delegate.parseCustomElement(ele);
                }
            }
        }
    }
    else {
        //Document的根節點沒有使用Spring默認的命名空間,則使用用戶自定義的
        //解析規則解析Document根節點
        delegate.parseCustomElement(root);
    }
}


//使用Spring的Bean規則解析Document元素節點
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>元素,
    //按照Spring的Bean規則解析元素
    else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
        processBeanDefinition(ele, delegate);
    }
    else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
        // recurse
        doRegisterBeanDefinitions(ele);
    }
}

//解析<Import>導入元素,從給定的導入路徑加載Bean定義資源到Spring IoC容器中
protected void importBeanDefinitionResource(Element ele) {
    //獲取給定的導入元素的location屬性
    String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
    //若是導入元素的location屬性值爲空,則沒有導入任何資源,直接返回
    if (!StringUtils.hasText(location)) {
        getReaderContext().error("Resource location must not be empty", ele);
        return;
    }

    // Resolve system properties: e.g. "${user.dir}"
    //使用系統變量值解析location屬性值
    location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);

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

    // Discover whether the location is an absolute or relative URI
    //標識給定的導入元素的location是不是絕對路徑
    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*:"
        //給定的導入元素的location不是絕對路徑
    }

    // Absolute or relative?
    //給定的導入元素的location是絕對路徑
    if (absoluteLocation) {
        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.
        //給定的導入元素的location是相對路徑
        try {
            int importCount;
            //將給定導入元素的location封裝爲相對路徑資源
            Resource relativeResource = getReaderContext().getResource().createRelative(location);
            //封裝的相對路徑資源存在
            if (relativeResource.exists()) {
                //使用資源讀入器加載Bean定義資源
                importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
                actualResources.add(relativeResource);
            }
            //封裝的相對路徑資源不存在
            else {
                //獲取Spring IOC容器資源讀入器的基本路徑
                String baseLocation = getReaderContext().getResource().getURL().toString();
                //根據Spring IOC容器資源讀入器的基本路徑加載給定導入路徑的資源
                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>元素以後,發送容器導入其餘資源處理完成事件
    getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}

/** * Process the given alias element, registering the alias with the registry. */
//解析<Alias>別名元素,爲Bean向Spring IoC容器註冊別名
protected void processAliasRegistration(Element ele) {
    //獲取<Alias>別名元素中name的屬性值
    String name = ele.getAttribute(NAME_ATTRIBUTE);
    //獲取<Alias>別名元素中alias的屬性值
    String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
    boolean valid = true;
    //<alias>別名元素的name屬性值爲空
    if (!StringUtils.hasText(name)) {
        getReaderContext().error("Name must not be empty", ele);
        valid = false;
    }
    //<alias>別名元素的alias屬性值爲空
    if (!StringUtils.hasText(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);
        }
        //在解析完<Alias>元素以後,發送容器別名處理完成事件
        getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
    }
}

/** * Process the given bean element, parsing the bean definition * and registering it with the registry. */
//解析Bean定義資源Document對象的普通元素
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    // BeanDefinitionHolder是對BeanDefinition的封裝,即Bean定義的封裝類
    //對Document對象中<Bean>元素的解析由BeanDefinitionParserDelegate實現
    // BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            // Register the final decorated instance.
            //向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);
        }
        // Send registration event.
        //在完成向Spring IOC容器註冊解析獲得的Bean定義以後,發送註冊事件
        getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }
}

經過上述Spring IOC容器對載入的Bean定義Document解析能夠看出,咱們使用Spring時,在Spring配置文件中可使用元素來導入 IOC 容器所須要的其餘資源,SpringIOC容器在解析時會首先將指定導入的資源加載進容器中。使用別名時,SpringIOC容器首先將別名元素所定義的別名註冊到容器中。對於既不是元素,又不是元素的元素,即Spring配置文件中普通的元素的解析由BeanDefinitionParserDelegate類的parseBeanDefinitionElement 方法來實現。app

2.11 BeanDefinitionParserDelegate解析Bean定義資源文件中的元素

Bean 定義資源文件中的和元素解析在DefaultBeanDefinitionDocumentReader中已經完成,對Bean定義資源文件中使用最多的元素交由 BeanDefinitionParserDelegate來解析,其解析實現的源碼以下:less

//解析<Bean>元素的入口
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
    return parseBeanDefinitionElement(ele, null);
}


//解析Bean定義資源文件中的<Bean>元素,這個方法中主要處理<Bean>元素的id,name和別名屬性
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
    //獲取<Bean>元素中的id屬性值
    String id = ele.getAttribute(ID_ATTRIBUTE);
    //獲取<Bean>元素中的name屬性值
    String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

    //獲取<Bean>元素中的alias屬性值
    List<String> aliases = new ArrayList<>();

    //將<Bean>元素中的全部name屬性值存放到別名中
    if (StringUtils.hasLength(nameAttr)) {
        String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
        aliases.addAll(Arrays.asList(nameArr));
    }

    String beanName = id;
    //若是<Bean>元素中沒有配置id屬性時,將別名中的第一個值賦值給beanName
    if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
        beanName = aliases.remove(0);
        if (logger.isDebugEnabled()) {
            logger.debug("No XML 'id' specified - using '" + beanName +
                    "' as bean name and " + aliases + " as aliases");
        }
    }

    //檢查<Bean>元素所配置的id或者name的惟一性,containingBean標識<Bean>
    //元素中是否包含子<Bean>元素
    if (containingBean == null) {
        //檢查<Bean>元素所配置的id、name或者別名是否重複
        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 {
                    //若是<Bean>元素中沒有配置id、別名或者name,且包含了子元素
                    //<Bean>元素,爲解析的Bean使用別名向IOC容器註冊
                    beanName = this.readerContext.generateBeanName(beanDefinition);
                    // Register an alias for the plain bean class name, if still possible,
                    // if the generator returned the class name plus a suffix.
                    // This is expected for Spring 1.2/2.0 backwards compatibility.
                    //爲解析的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或者別名是否重複
protected void checkNameUniqueness(String beanName, List<String> aliases, Element beanElement) {
    String foundName = null;

    if (StringUtils.hasText(beanName) && this.usedNames.contains(beanName)) {
        foundName = beanName;
    }
    if (foundName == null) {
        foundName = CollectionUtils.findFirstMatch(this.usedNames, aliases);
    }
    if (foundName != null) {
        error("Bean name '" + foundName + "' is already used in this <beans> element", beanElement);
    }

    this.usedNames.add(beanName);
    this.usedNames.addAll(aliases);
}


//詳細對<Bean>元素中配置的Bean定義其餘屬性進行解析
//因爲上面的方法中已經對Bean的id、name和別名等屬性進行了處理
//該方法中主要處理除這三個之外的其餘屬性數據
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
        Element ele, String beanName, @Nullable BeanDefinition containingBean) {
    //記錄解析的<Bean>
    this.parseState.push(new BeanEntry(beanName));

    //這裏只讀取<Bean>元素中配置的class名字,而後載入到BeanDefinition中去
    //只是記錄配置的class名字,不作實例化,對象的實例化在依賴注入時完成
    String className = null;

    //若是<Bean>元素中配置了parent屬性,則獲取parent屬性的值
    if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
        className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
    }
    String parent = null;
    if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
        parent = ele.getAttribute(PARENT_ATTRIBUTE);
    }

    try {
        //根據<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();
    }

    //解析<Bean>元素出錯時,返回null
    return null;
}

只要使用過 Spring,對 Spring 配置文件比較熟悉的人,經過對上述源碼的分析,就會明白咱們在Spring配置文件中元素的中配置的屬性就是經過該方法解析和設置到 Bean 中去的。ide

注意:在解析元素過程當中沒有建立和實例化 Bean 對象,只是建立了 Bean 對象的定義類BeanDefinition,將元素中的配置信息設置到 BeanDefinition 中做爲記錄,當依賴注入時才使用這些記錄信息建立和實例化具體的 Bean 對象。上面方法中一些對一些配置如元信息(meta)、qualifier 等的解析,咱們在 Spring 中配置時使用的也很少,咱們在使用 Spring 的元素時,配置最多的是屬性,所以咱們下面繼續分析源碼,瞭解 Bean 的屬性在解析時是如何設置的。post

因爲IOC 容器的初始化內容比較多一次文章沒法寫完,因此分了五篇進行講解此篇爲第三篇。ui

文檔有參考其餘資料,若是問題請聯繫我,進行刪除!謝謝!this

相關文章
相關標籤/搜索