博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
XmlBeanFactory
阅读量:6918 次
发布时间:2019-06-27

本文共 13590 字,大约阅读时间需要 45 分钟。

1.xmlBeanFactory构造

/**     * Create a new XmlBeanFactory with the given input stream,     * which must be parsable using DOM.     * @param resource XML resource to load bean definitions from     * @param parentBeanFactory parent bean factory     * @throws BeansException in case of loading or parsing errors     */    public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {        super(parentBeanFactory);        this.reader.loadBeanDefinitions(resource);    }

2.XmlBeanDefinitionReader加载bean定义

/**     * Load bean definitions from the specified XML file.     * @param resource the resource descriptor for the XML file     * @return the number of bean definitions found     * @throws BeanDefinitionStoreException in case of loading or parsing errors     */    @Override    public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {        return loadBeanDefinitions(new EncodedResource(resource));    }
/**     * Load bean definitions from the specified XML file.     * @param encodedResource the resource descriptor for the XML file,     * allowing to specify an encoding to use for parsing the file     * @return the number of bean definitions found     * @throws BeanDefinitionStoreException in case of loading or parsing errors     */    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
currentResources = this.resourcesCurrentlyBeingLoaded.get(); if (currentResources == null) { currentResources = new HashSet
(4); this.resourcesCurrentlyBeingLoaded.set(currentResources); } if (!currentResources.add(encodedResource)) { throw new BeanDefinitionStoreException( "Detected cyclic loading of " + encodedResource + " - check your import definitions!"); } try { InputStream inputStream = encodedResource.getResource().getInputStream(); try { InputSource inputSource = new InputSource(inputStream); if (encodedResource.getEncoding() != null) { inputSource.setEncoding(encodedResource.getEncoding()); } return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); } finally { 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(); } } }
/**     * Actually load bean definitions from the specified XML file.     * @param inputSource the SAX InputSource to read from     * @param resource the resource descriptor for the XML file     * @return the number of bean definitions found     * @throws BeanDefinitionStoreException in case of loading or parsing errors     * @see #doLoadDocument     * @see #registerBeanDefinitions     */    protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)            throws BeanDefinitionStoreException {        try {            Document doc = doLoadDocument(inputSource, resource);            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);        }    }
/**     * Register the bean definitions contained in the given DOM document.     * Called by {
@code loadBeanDefinitions}. *

Creates a new instance of the parser class and invokes * {

@code registerBeanDefinitions} on it. * @param doc the DOM document * @param resource the resource descriptor (for context information) * @return the number of bean definitions found * @throws BeanDefinitionStoreException in case of parsing errors * @see #loadBeanDefinitions * @see #setDocumentReaderClass * @see BeanDefinitionDocumentReader#registerBeanDefinitions */ public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException { BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); documentReader.setEnvironment(this.getEnvironment()); int countBefore = getRegistry().getBeanDefinitionCount(); documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); return getRegistry().getBeanDefinitionCount() - countBefore; }

3.DefaultBeanDefinitionDocumentReader解析器注册bean definition,

/**     * {
@inheritDoc} *

This implementation parses bean definitions according to the "spring-beans" XSD * (or DTD, historically). *

Opens a DOM Document; then initializes the default settings * specified at the {

@code
} level; then parses the contained bean definitions. */ @Override public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) { this.readerContext = readerContext; logger.debug("Loading bean definitions"); Element root = doc.getDocumentElement(); doRegisterBeanDefinitions(root); }

/**     * Register each bean definition within the given root {
@code
} element. * @throws IllegalStateException if {
@code
elements will cause recursion in this method. In // order to propagate and preserve
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. BeanDefinitionParserDelegate parent = this.delegate; this.delegate = createDelegate(this.readerContext, root, parent); preProcessXml(root); parseBeanDefinitions(root, this.delegate); postProcessXml(root); this.delegate = parent; }
/**     * Parse the elements at the root level in the document:     * "import", "alias", "bean".     * @param root the DOM root element of the document     */    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);        }    }
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {        if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {            importBeanDefinitionResource(ele);        }        else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {            processAliasRegistration(ele);        }        else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {            processBeanDefinition(ele, delegate);        }        else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {            // recurse            doRegisterBeanDefinitions(ele);        }    }
/**     * Process the given bean element, parsing the bean definition     * and registering it with the registry.     */    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {        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));        }    }

4.BeanDefinitionReaderUtils

/**     * Register the given bean definition with the given bean factory.     * @param definitionHolder the bean definition including name and aliases     * @param registry the bean factory to register with     * @throws BeanDefinitionStoreException if registration failed     */    public static void registerBeanDefinition(            BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)            throws BeanDefinitionStoreException {        // Register bean definition under primary name.        String beanName = definitionHolder.getBeanName();        registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());        // Register aliases for bean name, if any.        String[] aliases = definitionHolder.getAliases();        if (aliases != null) {            for (String aliase : aliases) {                registry.registerAlias(beanName, aliase);            }        }    }

5.DefaultListableBeanFactory

//---------------------------------------------------------------------    // Implementation of BeanDefinitionRegistry interface    //---------------------------------------------------------------------    @Override    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)            throws BeanDefinitionStoreException {        Assert.hasText(beanName, "Bean name must not be empty");        Assert.notNull(beanDefinition, "BeanDefinition must not be null");        if (beanDefinition instanceof AbstractBeanDefinition) {            try {                ((AbstractBeanDefinition) beanDefinition).validate();            }            catch (BeanDefinitionValidationException ex) {                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,                        "Validation of bean definition failed", ex);            }        }        synchronized (this.beanDefinitionMap) {            BeanDefinition oldBeanDefinition = this.beanDefinitionMap.get(beanName);            if (oldBeanDefinition != null) {                if (!this.allowBeanDefinitionOverriding) {                    throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,                            "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +                            "': There is already [" + oldBeanDefinition + "] bound.");                }                else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {                    // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE                    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 (this.logger.isInfoEnabled()) {                        this.logger.info("Overriding bean definition for bean '" + beanName +                                "': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");                    }                }            }            else {                this.beanDefinitionNames.add(beanName);                this.frozenBeanDefinitionNames = null;            }            this.beanDefinitionMap.put(beanName, beanDefinition);        }        resetBeanDefinition(beanName);    }

 

转载于:https://www.cnblogs.com/shapeOfMyHeart/p/5052756.html

你可能感兴趣的文章
JCheckBox使用示例
查看>>
OEA 框架中集成的 RDLC 报表介绍
查看>>
[铁道部信息化管理]12306的已知信息、数据及问题
查看>>
web前端开发分享-css,js深化篇
查看>>
在CentOS下安装tomcat并配置环境变量(改默认端口8080为8081)
查看>>
AgileEAS.NET平台开发案例-药店系统-需求分析
查看>>
[Android] adb 命令 dumpsys activity , 用来看 task 中的activity。 (uninstall virus)
查看>>
MyBatis简单使用和入门理解
查看>>
图片移动效果
查看>>
基于Web的Kafka管理器工具之Kafka-manager安装之后第一次进入web UI的初步配置(图文详解)...
查看>>
C# Winform反序列化复杂json字符串
查看>>
SilverLight:布局(1) Border(边框)对象、Grid(网格)对象
查看>>
MonoBehaviour.print和Debug.Log是同样的作用
查看>>
SAP 接口概述
查看>>
BW Delta (增量)更新方法 .
查看>>
5.2. WebRTC
查看>>
Java的注解机制——Spring自动装配的实现原理
查看>>
正式生产环境下hadoop集群的DNS+NFS+ssh免password登陆配置
查看>>
SQL Server数据库大型应用解决方案总结
查看>>
[Think]故事几则
查看>>