我们上一篇文章最后调用到 `org.springframework.beans.factory.xml. XmlBeanDefinitionReader#doLoadDocument(...)

` 方法,该方法主要代码如下:

protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
//getValidationModeForResource是数据验证模型
return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
getValidationModeForResource(resource), isNamespaceAware());
}

我们这篇文章主要以 #getValidationModeForResource(...) 方法作为切入,来分析一下验证模型的主要方法,关于spring中的数据验证、绑定等内容我们在后面文章一点点的来挖掘

1.getValidationModeForResource

/**
* 禁止只用验证模型
* Indicates that the validation should be disabled.
*/
public static final int VALIDATION_NONE = XmlValidationModeDetector.VALIDATION_NONE;
/**
* 使用自动检测验证模型
* Indicates that the validation mode should be detected automatically.
*/
public static final int VALIDATION_AUTO = XmlValidationModeDetector.VALIDATION_AUTO;
/**
* 使用DTD验证模型
* Indicates that DTD validation should be used.
*/
public static final int VALIDATION_DTD = XmlValidationModeDetector.VALIDATION_DTD;
/**
* 使用XSD验证模型
* Indicates that XSD validation should be used.
*/
public static final int VALIDATION_XSD = XmlValidationModeDetector.VALIDATION_XSD;
/**
* 确定当前 resource资源需要的验证模型 默认自动模式
* 如果显式的配置了验证模型,则用配置的,如果没有则从Resource中来获取
* Determine the validation mode for the specified {@link Resource}.
* If no explicit validation mode has been configured, then the validation
* mode gets {@link #detectValidationMode detected} from the given resource.
* <p>Override this method if you would like full control over the validation
* mode, even when something other than {@link #VALIDATION_AUTO} was set.
* @see #detectValidationMode
*/
protected int getValidationModeForResource(Resource resource) {
// <1> 获取指定的验证模式
int validationModeToUse = getValidationMode();
// <2> 如果有指定的模式 则直接返回,
if (validationModeToUse != VALIDATION_AUTO) {
return validationModeToUse;
}
//<3> 没有指定的 那么通resource中去获取
int detectedMode = detectValidationMode(resource);
if (detectedMode != VALIDATION_AUTO) {
return detectedMode;
}
// <4> 若以上都不满足则使用XSD模式
// Hmm, we didn't get a clear indication... Let's assume XSD,
// since apparently no DTD declaration has been found up until
// detection stopped (before finding the document's root tag).
return VALIDATION_XSD;
}

对上述代码我们做简单分析

  • <1>处调用 #getValidationMode() 方法来获取指定的验证模式 ,这里的 validationMode 如果是外部手动设置的,那么就直接返回,
/**
* Set the validation mode to use. Defaults to {@link #VALIDATION_AUTO}.
* <p>Note that this only activates or deactivates validation itself.
* If you are switching validation off for schema files, you might need to
* activate schema namespace support explicitly: see {@link #setNamespaceAware}.
*/
public void setValidationMode(int validationMode) {
this.validationMode = validationMode;
}
/**
* Return the validation mode to use.
*/
public int getValidationMode() {
return this.validationMode;
}
  • <3>处调用 #detectValidationMode() 方法来自动获取验证模型,代码如下:
/**
* 进行自动检测指定的XML用那种检测模型
* Detect which kind of validation to perform on the XML file identified
* by the supplied {@link Resource}. If the file has a {@code DOCTYPE}
* definition then DTD validation is used otherwise XSD validation is assumed.
* <p>Override this method if you would like to customize resolution
* of the {@link #VALIDATION_AUTO} mode.
*/
protected int detectValidationMode(Resource resource) {
// <1> 资源是否打开
if (resource.isOpen()) {
throw new BeanDefinitionStoreException(
"Passed-in Resource [" + resource + "] contains an open stream: " +
"cannot determine validation mode automatically. Either pass in a Resource " +
"that is able to create fresh streams, or explicitly specify the validationMode " +
"on your XmlBeanDefinitionReader instance.");
}
InputStream inputStream;
try {
inputStream = resource.getInputStream();
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"Unable to determine validation mode for [" + resource + "]: cannot open InputStream. " +
"Did you attempt to load directly from a SAX InputSource without specifying the " +
"validationMode on your XmlBeanDefinitionReader instance?", ex);
}
try {
////<2> 调用XmlValidationModeDetector 中的真实实现 传入 inputStream
return this.validationModeDetector.detectValidationMode(inputStream);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("Unable to determine validation mode for [" +
resource + "]: an error occurred whilst reading from the InputStream.", ex);
}
}

2.detectValidationMode

上面 <3>处调用了 #detectValidationMode() 方法,这里 validationModeDetector 对象是类中的一个不可变成员变量 定义如下:

private final XmlValidationModeDetector validationModeDetector = new XmlValidationModeDetector();

#detectValidationMode() 方法的具体实现如下:

/**
* 通过指定的 inputStream 来检测 XML 中的验证模型
* Detect the validation mode for the XML document in the supplied {@link InputStream}.
* Note that the supplied {@link InputStream} is closed by this method before returning.
* @param inputStream the InputStream to parse
* @throws IOException in case of I/O failure
* @see #VALIDATION_DTD
* @see #VALIDATION_XSD
*/
public int detectValidationMode(InputStream inputStream) throws IOException {
//<1> 通过 BufferedReader 读取inputStream
// Peek into the file to look for DOCTYPE.
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
//<2> 是否是DTD验证模式 ,默认否
boolean isDtdValidated = false;
String content;
// <3> 逐行读取内容
while ((content = reader.readLine()) != null) {
content = consumeCommentTokens(content);
// <4> 如果是注释或者为空这跳过
if (this.inComment || !StringUtils.hasText(content)) {
continue;
}
// <5> 校验是否包含 DOCTYPE 若包含则为DTD模式
if (hasDoctype(content)) {
isDtdValidated = true;
break;
}
// <6> 校验是否是打开的标签, 如果一行有 < 并且后面跟着是字母,那么返回
if (hasOpeningTag(content)) {
// End of meaningful data...
break;
}
}
// 确定解析方式
return (isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD);
}
catch (CharConversionException ex) {
// Choked on some character encoding...
// Leave the decision up to the caller.
return VALIDATION_AUTO;
}
finally {
//关闭流
reader.close();
}
}
  • 上述代码中<5>处校验是否包含了 DOCTYPE 字符,具体代码如下:
/**
* The token in a XML document that declares the DTD to use for validation
* and thus that DTD validation is being used.
*/
private static final String DOCTYPE = "DOCTYPE";
/**
* 判断是否包含 DOCTYPE
* Does the content contain the DTD DOCTYPE declaration?
*/
private boolean hasDoctype(String content) {
return content.contains(DOCTYPE);
}
  • <6>处进行了标签的打开判断,代码如下:
/**
* Does the supplied content contain an XML opening tag. If the parse state is currently
* in an XML comment then this method always returns false. It is expected that all comment
* tokens will have consumed for the supplied content before passing the remainder to this method.
*/
private boolean hasOpeningTag(String content) {
if (this.inComment) {
return false;
}
int openTagIndex = content.indexOf('<'); // 获取字符中 < 的索引
return (openTagIndex > -1 // 存在 <
&& (content.length() > openTagIndex + 1) // 并且后面还有内容
&&Character.isLetter(content.charAt(openTagIndex + 1)));//后面必须是字母
}
  • 如果抛出异常时 CharConversionException 则默认设置为自动 VALIDATION_AUTO

本文由AnonyStar 发布,可转载但需声明原文出处。

仰慕「优雅编码的艺术」 坚信熟能生巧,努力改变人生

欢迎关注微信公账号 :云栖简码 获取更多优质文章

更多文章关注笔者博客 :云栖简码

《spring源码解读》 - ioc之验证模型获取的更多相关文章

  1. spring源码解读-ioc

    本系列博客结合我的理解,对spring的ioc进行简单分析,欢迎大家批评指正. beanfactory 我们从beanfactory开始,beanfactory是最根部的容器,描述了整个ioc的一些规 ...

  2. spring源码浅析——IOC

    =========================================== 原文链接: spring源码浅析--IOC   转载请注明出处! ======================= ...

  3. spring源码分析---IOC(1)

    我们都知道spring有2个最重要的概念,IOC(控制反转)和AOP(依赖注入).今天我就分享一下spring源码的IOC. IOC的定义:直观的来说,就是由spring来负责控制对象的生命周期和对象 ...

  4. Spring源码解析-ioc容器的设计

    Spring源码解析-ioc容器的设计 1 IoC容器系列的设计:BeanFactory和ApplicatioContext 在Spring容器中,主要分为两个主要的容器系列,一个是实现BeanFac ...

  5. Spring源码剖析4:其余方式获取Bean的过程分析

    原型Bean加载过程 之前的文章,分析了非懒加载的单例Bean整个加载过程,除了非懒加载的单例Bean之外,Spring中还有一种Bean就是原型(Prototype)的Bean,看一下定义方式: 1 ...

  6. Spring 源码剖析IOC容器(一)概览

    目录 一.容器概述 二.核心类源码解读 三.模拟容器获取Bean ======================= 一.容器概述 spring IOC控制反转,又称为DI依赖注入:大体是先初始化bean ...

  7. Spring源码 05 IOC 注解方式

    参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...

  8. Spring源码 07 IOC refresh方法2

    参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...

  9. Spring源码 06 IOC refresh方法1

    参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...

  10. Spring源码 04 IOC XML方式

    参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...

随机推荐

  1. Python里的目录方法

    Python里的目录_文件.目录相关的方法: mkdir(目录名): 在当前目录下创建新的目录 程序: import os # 创建新的目录-包结构 os.mkdir('新目录-test') getc ...

  2. logging日志基础示例

    import logging logger = logging.getLogger() # 获取日志对象 logfile = 'test.log' hdlr = logging.FileHandler ...

  3. [C#] (原创)一步一步教你自定义控件——01,TrackBar

    一.前言 技术没有先进落后之分,只有合不合适. WinForm有着非常多的优点,在使用WinForm久了之后,难免会觉得WinForm自带的某些控件外观上有些许朴素.或者功能上有些不如意,自然而然便想 ...

  4. linux的文件处理(匹配 正则表达式 egrep awk sed)和系统、核心数据备份

    文件处理 1.处理方式 匹配 正则表达式 egrep awk sed 2.文件中的处理字符 \n  新行符 换行 \t  制表符 tab键 缺省8个空格 \b  退格符 backspace键 退格键 ...

  5. react-router-dom中Switch和exact

    路由地址: 内容: / 根 /user  用户 /user/hh 用户笑了 先说exact:(此时没有Switch),给 / 设置exact精确匹配 地址栏: /user/hh 渲染2个组件 : 用户 ...

  6. 创建githup远程库并关联

    第一种方法:远程new仓库时直接勾选初始化仓库,然后克隆到本地即可(注:本地对应层不可再初始化仓库git init).克隆下来的仓库已经与远程库建立了管理git removte 第二种方法:本地下面有 ...

  7. 详解Flask上下文

    上下文是在Flask开发中的一个核心概念,本文将通过阅读源码分享下其原理和实现. Flask系列文章: Flask开发初探 WSGI到底是什么 Flask源码分析一:服务启动 Flask路由内部实现原 ...

  8. C++Primer学习日记

    计划:4.27-4.30 完成IO库.顺序容器两章 4/28 ------------------------------------------------- 为什么要使用using namespa ...

  9. 企业级Gitlab-ci实践

    前言 吐槽一波 2020年6月2号刚入职公司时,第一感觉是集群环境是个大坑!内网一套,公网一套.内网采用单节点Kubernetes,公网采用aliyun托管的X节点Kubernetes(还有节点是2C ...

  10. 数据结构C++使用邻接表实现图

    定义邻接表存储的图类.[实验要求] (1)创建一个邻接表存储的图:(2)返回图中指定边的权值:(3)插入操作:向图中插入一个顶点,插入一条边:(4)删除操作:从图中删除一个顶点,删除一条边:(5)图的 ...