(二)BeanDefinition的定位,加載和註冊

XmlWebApplicationContext爲例,分析容器初始化過程當中一個BeanDefinition的定位,加載和註冊過程java

  • Resource定位。使用ResourceLoader定位到資源
  • 加載。BeanDefinitionReader解析資源中的bean的定義信息並建立BeanDefinition對象
  • 註冊。使用BeanDefinitionRegistry,在容器內部將BeanDefinition對象註冊進來

定位

定位的棧

如下是調用refresh()方法定位Resource的棧信息node

loadBeanDefinitions:219, AbstractBeanDefinitionReader (org.springframework.beans.factory.support)
loadBeanDefinitions:194, AbstractBeanDefinitionReader (org.springframework.beans.factory.support)
loadBeanDefinitions:125, XmlWebApplicationContext (org.springframework.web.context.support)
loadBeanDefinitions:94, XmlWebApplicationContext (org.springframework.web.context.support)
refreshBeanFactory:133, AbstractRefreshableApplicationContext (org.springframework.context.support)
obtainFreshBeanFactory:621, AbstractApplicationContext (org.springframework.context.support)
refresh:522, AbstractApplicationContext (org.springframework.context.support)
...

定位流程

調用BeanDefinitionReader持有的ResourceLoader對象的Resource getResource(String var1);方法獲取到Resourceweb

ps:在Applicationcontext的繼承體系中,Applicationcontext實現了ResourceLoader,因此容器也是一個ResourceLoader。一般BeanDefinitionReader持有的ResourceLoader對象就是當前使用的容器spring

loadBeanDefinitions:94, XmlWebApplicationContext (org.springframework.web.context.support)

下面的方法對應此棧,方法實如今XmlWebApplicationContextide

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    // 建立一個XmlBeanDefinitionReader,用於定位Bean定義信息
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

    beanDefinitionReader.setEnvironment(getEnvironment());
    // XmlWebApplicationContext的繼承體系中實現了ResourceLoader,因此this是一個ResourceLoader
    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);
}

上述方法建立了一個BeanDefinitionReader,並將容器做爲ResourceLoader傳遞進去ui

loadBeanDefinitions:219, AbstractBeanDefinitionReader (org.springframework.beans.factory.support)

下面的方法對應此棧,調用方法的是上一步建立的XmlBeanDefinitionReader對象,方法實如今AbstractBeanDefinitionReaderthis

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
    ResourceLoader resourceLoader = getResourceLoader();
    if (resourceLoader == null) {
        throw new BeanDefinitionStoreException("...");
    }

    if (resourceLoader instanceof ResourcePatternResolver) {
        try {
            // 至此,完成BeanDefinition的Resource的定位。獲取到Resource
            Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
            // BenaDefinition的加載和註冊在此方法中
            int loadCount = loadBeanDefinitions(resources);
            if (actualResources != null) {
                for (Resource resource : resources) {
                    actualResources.add(resource);
                }
            }
            return loadCount;
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException("...", ex);
        }
    }
    else {
        // 至此,完成BeanDefinition的Resource的定位。獲取到Resource
        Resource resource = resourceLoader.getResource(location);
        // BenaDefinition的加載和註冊均在此方法中
        int loadCount = loadBeanDefinitions(resource);
        if (actualResources != null) {
            actualResources.add(resource);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("...");
        }
        return loadCount;
    }
}

加載

加載的棧

// 此方法包含BeanDefinition的加載和註冊
processBeanDefinition:305, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
parseDefaultElement:196, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
parseBeanDefinitions:175, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
doRegisterBeanDefinitions:148, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
registerBeanDefinitions:98, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
registerBeanDefinitions:507, XmlBeanDefinitionReader (org.springframework.beans.factory.xml)
// 此方法包含了BeanDefinition加載的兩大步驟(解析xml文件建立Document對象,BeanDefinition加載和註冊)
doLoadBeanDefinitions:391, XmlBeanDefinitionReader (org.springframework.beans.factory.xml)
loadBeanDefinitions:335, XmlBeanDefinitionReader (org.springframework.beans.factory.xml)
loadBeanDefinitions:303, XmlBeanDefinitionReader (org.springframework.beans.factory.xml)
loadBeanDefinitions:187, AbstractBeanDefinitionReader (org.springframework.beans.factory.support)
// 這裏包含BeanDefinition的定位,同時也包含BeanDefinition的加載和註冊的入口方法
loadBeanDefinitions:223, AbstractBeanDefinitionReader (org.springframework.beans.factory.support)
...
refresh:522, AbstractApplicationContext (org.springframework.context.support)
...

加載流程

加載分爲兩步spa

  1. 使用XML的解析器獲取到Document對象(須要解析xml文件是由於bean的定義信息是在xml文件裏寫的)
  2. 使用DocumentReader按照Spring定義Bean的規則解析xml文件並建立BeanDefinition對象。建立的BeanDefinition對象會先被BeanDefinitionHolder封裝起來
doLoadBeanDefinitions:391, XmlBeanDefinitionReader (org.springframework.beans.factory.xml)

下面的方法對應此棧,方法實如今XmlBeanDefinitionReaderdebug

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException {
    try {
        // 解析xml文件,建立Document對象
        Document doc = doLoadDocument(inputSource, resource);
        // BeanDefinition的加載和註冊
        return registerBeanDefinitions(doc, resource);
    }
    catch (Throwable ex) {
        throw ...
    }
}
parseBeanDefinitions:175, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)

下面的方法對應此棧。獲取xml中的根節點,獲取根節點下的全部子節點,遍歷code

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);
		}
	}
processBeanDefinition:305, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)

下面的方法對應此棧。方法的調用者DefaultBeanDefinitionDocumentReader是由XmlBeanDefinitionReader建立的

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    // 至此,完成BeanDefinition的加載。建立BeanDefinition對象並將結果交給BeanDefinitionHolder持有
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            // BeanDefinition的註冊在此方法中
            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));
    }
}

註冊

註冊的棧

registerBeanDefinition:792, DefaultListableBeanFactory (org.springframework.beans.factory.support)
registerBeanDefinition:150, BeanDefinitionReaderUtils (org.springframework.beans.factory.support)
processBeanDefinition:310, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
parseDefaultElement:196, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
parseBeanDefinitions:175, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
doRegisterBeanDefinitions:148, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
registerBeanDefinitions:98, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)
registerBeanDefinitions:507, XmlBeanDefinitionReader (org.springframework.beans.factory.xml)
// 此方法包含了BeanDefinition加載的兩大步驟(解析xml文件建立Document對象,BeanDefinition加載和註冊)
doLoadBeanDefinitions:391, XmlBeanDefinitionReader (org.springframework.beans.factory.xml)
...

註冊流程

以kv鍵值對的方式將beanName和BeanDefinition對象put到容器內部的一個map中(類型是ConcurrentHashMap

processBeanDefinition:310, DefaultBeanDefinitionDocumentReader (org.springframework.beans.factory.xml)

下面的方法對應此棧

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    // 建立BeanDefinition並將其包裝在BeanDefinitionHolder中
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            // 將BeanDefinition註冊到容器中
            // 方法的第二個參數是DefaultListableBeanFactory對象
            BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
        }
        catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("...", ele, ex);
        }
        // 發佈註冊事件
        getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }
}
registerBeanDefinition:150, BeanDefinitionReaderUtils (org.springframework.beans.factory.support)

下面的方法對應此棧。這裏的BeanDefinitionRegistry的實際類型是DefaultListableBeanFactory

public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException {

    String beanName = definitionHolder.getBeanName();
    // 調用BeanDefinitionRegistry(Bean定義信息註冊中心)將BeanDefinition以kv形式註冊到容器中。k是beanName,v是對象
    registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

    String[] aliases = definitionHolder.getAliases();
    if (aliases != null) {
        for (String alias : aliases) {
            // 把別名也註冊到容器中
            registry.registerAlias(beanName, alias);
        }
    }
}
registerBeanDefinition:792, DefaultListableBeanFactory (org.springframework.beans.factory.support)

下面的方法對應此棧。方法實如今DefaultListableBeanFactory,方法由BeanDefinitionRegistry接口定義

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {

    if (beanDefinition instanceof AbstractBeanDefinition) {
        try {
            ((AbstractBeanDefinition) beanDefinition).validate();
        }
        catch (BeanDefinitionValidationException ex) {
            throw ...
        }
    }

    BeanDefinition oldBeanDefinition;

    // 先用beanName從容器中獲取BeanDefinition
    oldBeanDefinition = this.beanDefinitionMap.get(beanName);
    // 若是容器中確實已經存在同名BeanDefinition對象,根據以前設置的可否覆蓋同名對象進行操做
    if (oldBeanDefinition != null) {
        // 若是設置的是  不能覆蓋同名對象,拋異常
        if (!isAllowBeanDefinitionOverriding()) {
            throw new ...
        }
        else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
           ...
        }
        else if (!beanDefinition.equals(oldBeanDefinition)) {
            ...
        }
        else {
            ...
        }
        // 若是 能覆蓋同名對象,將beanDefinition對象put到map中
        // 這個map就是容器中BeanDefinition的持有者,
        this.beanDefinitionMap.put(beanName, beanDefinition);
    }
    else {
        if (hasBeanCreationStarted()) {
            synchronized (this.beanDefinitionMap) {
                // 將beanDefinition對象put到map中
                this.beanDefinitionMap.put(beanName, beanDefinition);
                List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
                updatedDefinitions.addAll(this.beanDefinitionNames);
                updatedDefinitions.add(beanName);
                this.beanDefinitionNames = updatedDefinitions;
                if (this.manualSingletonNames.contains(beanName)) {
                    Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
                    updatedSingletons.remove(beanName);
                    this.manualSingletonNames = updatedSingletons;
                }
            }
        }
        else {
            // 將beanDefinition對象put到map中
            this.beanDefinitionMap.put(beanName, beanDefinition);
            this.beanDefinitionNames.add(beanName);
            this.manualSingletonNames.remove(beanName);
        }
        this.frozenBeanDefinitionNames = null;
    }

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

此方法會將BeanDefinition對象put到map中

至此,一個BeanDefinition註冊到容器中的任務就完成了

相關文章
相關標籤/搜索