spring加载xml验证文件(dtd,xsd)分析

入口

正如我们所知,spring容器启动会经历如下几个步骤:
1、定位,定位到资源文件,并且解析为Resource对象
2、加载,加载xml,将xml文件解析为对应的BeanDefinition
3、注册,注册对应的BeanDefinition
下面以AbstractXmlApplicationContext.loadBeanDefinitions为入口进行分析:

    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        //为当前工厂创建xml解析器
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // Configure the bean definition reader with this context's
        // resource loading environment.
        //通过上下文的资源加载环境配置bean解析器
        beanDefinitionReader.setEnvironment(this.getEnvironment());//配置当前环境
        beanDefinitionReader.setResourceLoader(this);//配置资源解析器
        //配置schemas或者dtd的资源解析器,EntityResolver维护了url->schemalocation的路径
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        // Allow a subclass to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        //子类提供自定义的reader的初始化方法
        initBeanDefinitionReader(beanDefinitionReader);
        //加载bean定义
        loadBeanDefinitions(beanDefinitionReader);
    }

定位到beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
ResouceEntityResolver,该类往上追述可知父类为EntityResolver。

何为EntityResolver

如果SAX应用程序需要实现自定义处理外部实体,则必须实现此接口,并使用setEntityResolver方法向SAX 驱动器注册一个实例.也就是说,对于解析一个xml,sax首先会读取该xml文档上的声明,根据声明去寻找相应的dtd定义,以便对文档的进行验证,默认的寻找规则,(即:通过网络,实现上就是声明DTD的地址URI地址来下载DTD声明),并进行认证,下载的过程是一个漫长的过程,而且当网络不可用时,这里会报错,就是应为相应的dtd没找到,

EntityResolver 的作用

就是项目本身就可以提供一个如何寻找DTD/XSD的声明方法
即:由程序来实现寻找DTD/XSD声明的过程,比如我们将DTD/XSD放在项目的某处在实现时直接将此文档读取并返回个SAX即可,这样就避免了通过网络来寻找DTD/XSD的声明
查看EntityResolver的接口

public interface EntityResolver {  
public abstract InputSource resolveEntity (String publicId,
                                               String systemId)
        throws SAXException, IOException;

}

传入的参数为publicId以及systemId:

对于DTD解析的配置文件:




        ...

publicId=-//SPRING//DTD BEAN//EN
systemId=http://www.springframework.org/dtd/spring-beans.dtd

对于xsd解析的配置文件:



...
 

publicId=null
systemId=http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

spring获取xml验证文件的过程

spring在获取验证文件(dtd或者xsd)的时候,先读取xml的声明,判断采用dtd还是xsd的方式进行读取:
追述ResourceEntityResolver的父类,可得父类为DelegatingEntityResolver,该类维护了两个属性:

    private final EntityResolver dtdResolver;//dtd解析器

    private final EntityResolver schemaResolver;//xsd解析器
    
        public DelegatingEntityResolver(@Nullable ClassLoader classLoader) {
        this.dtdResolver = new BeansDtdResolver();//DTD解析器
        this.schemaResolver = new PluggableSchemaResolver(classLoader);//schema解析器
    }
    //读取xml声明,如果有.dtd后缀,调用dtd解析器;如果.xsd后缀,调用schema解析器
    public InputSource resolveEntity(String publicId, @Nullable String systemId) throws SAXException, IOException {
        if (systemId != null) {
            if (systemId.endsWith(DTD_SUFFIX)) {
                return this.dtdResolver.resolveEntity(publicId, systemId);
            }
            else if (systemId.endsWith(XSD_SUFFIX)) {
                return this.schemaResolver.resolveEntity(publicId, systemId);
            }
        }
        return null;
    }

spring根据xml声明,将解析的任务委托给dtd解析器BeansDtdResolver或者PluggableSchemaResolver;

BeansDtdResolver解析

spring加载xml验证文件(dtd,xsd)分析_第1张图片
1538990352061.png

它会寻找当前classpath路径下spring-beans.dtd文件:/org/springframework/beans/factory/xml/spring-beans.dtd


spring加载xml验证文件(dtd,xsd)分析_第2张图片
1538990352066.png

PluggableSchemaResolver解析

//读取路径,META-INF/spring.schemas
public static final String DEFAULT_SCHEMA_MAPPINGS_LOCATION = "META-INF/spring.schemas";
//将schemas路径以URL->filepath的形式存储
private volatile Map schemaMappings;

首先,PluggableSchemaResolver会加载META-INF/spring.schemas下所有schemas的信息存储在schemaMappings

    private Map getSchemaMappings() {
        Map schemaMappings = this.schemaMappings;
        //双重锁检查
        if (schemaMappings == null) {
            synchronized (this) {
                schemaMappings = this.schemaMappings;
                if (schemaMappings == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Loading schema mappings from [" + this.schemaMappingsLocation + "]");
                    }
                    try {
                        //加载路径为META-INF/spring.schemas,以Properties形式存储
                        Properties mappings =
                                PropertiesLoaderUtils.loadAllProperties(this.schemaMappingsLocation, this.classLoader);
                        if (logger.isDebugEnabled()) {
                            logger.debug("Loaded schema mappings: " + mappings);
                        }
                        //将加载的内容转成map
                        Map mappingsToUse = new ConcurrentHashMap<>(mappings.size());
                        CollectionUtils.mergePropertiesIntoMap(mappings, mappingsToUse);
                        schemaMappings = mappingsToUse;
                        //使用schemaMappings存储
                        this.schemaMappings = schemaMappings;
                    }
                    catch (IOException ex) {
                        throw new IllegalStateException(
                                "Unable to load schema mappings from location [" + this.schemaMappingsLocation + "]", ex);
                    }
                }
            }
        }
        return schemaMappings;
    }

如何解析对应xsd文件

    public InputSource resolveEntity(String publicId, @Nullable String systemId) throws IOException {
        if (logger.isTraceEnabled()) {
            logger.trace("Trying to resolve XML entity with public id [" + publicId +
                    "] and system id [" + systemId + "]");
        }

        if (systemId != null) {
            //根据URL即systemid,找到本地xsd文件的存储路径
            String resourceLocation = getSchemaMappings().get(systemId);
            if (resourceLocation != null) {
                //将对应xsd文件转为Resource
                Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
                try {
                    InputSource source = new InputSource(resource.getInputStream());
                    source.setPublicId(publicId);
                    source.setSystemId(systemId);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
                    }
                    return source;
                }
                catch (FileNotFoundException ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Couldn't find XML schema [" + systemId + "]: " + resource, ex);
                    }
                }
            }
        }
        return null;
    }

因此,此类一共做了这么几件事:
1、将spring-schemas的信息以URL->schemalocation的形式存储在map中,如图


spring加载xml验证文件(dtd,xsd)分析_第3张图片
1538991356375.png

spring加载xml验证文件(dtd,xsd)分析_第4张图片
1538991475107.png

2、通过xml声明的systemid,可以获取到对应xsd文件在当前路径下的地址,然后进行加载

你可能感兴趣的:(spring加载xml验证文件(dtd,xsd)分析)