Spring 配置文件xml文档的schema约束

在使用spring框架的时候,对于其配置文件xml,只是知道其使用方法,而不知道为什么。

这里来研究一下下。

1.配置文件示例

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"        
    xmlns:mvc="http://www.springframework.org/schema/mvc"     
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"              
    xsi:schemaLocation="                                               
            http://www.springframework.org/schema/beans    
            http://www.springframework.org/schema/beans/spring-beans.xsd    
            http://www.springframework.org/schema/context     
            http://www.springframework.org/schema/context/spring-context.xsd    
            http://www.springframework.org/schema/mvc    
            http://www.springframework.org/schema/mvc/spring-mvc.xsd  
            http://www.springframework.org/schema/tx   
            http://www.springframework.org/schema/tx/spring-tx.xsd  
            http://www.springframework.org/schema/aop  
            http://www.springframework.org/schema/aop/spring-aop.xsd ">  
</beans>  

上面是我们最常用的 applicationContext.xml 的配置文件的头部,很多时候我们只是知道这些必须添加,但为什么,添加哪些都不知道。

我们知道spring在启动的时候会验证 xml文档,这些引入的schema即用来验证配置文件的xml文档语法的正确性。

下面先来看看如何验证xml文档验证的相关知识。

2.xml的schema约束

schema定义

Schema的作用是定义一份XML文档中的可以正确使用的标签组。

就像文档类型定义(document type declaration 外语缩写:DTD)的作用一样,一份XML Schema定义了:

  1. 可以出现在文档里的元素;
  2. 可以出现在文档里的属性;
  3. 哪些元素是子元素;
  4. 子元素的顺序;
  5. 子元素的数量;
  6. 一个元素应是否能包含文本,或应该是空的;
  7. 元素和属性的数据类型;
  8. 元素和属性的默认值和固定值。

XML Schema 是 DTD 的升级版

XML Schema 是用来取代 DTD 的 。

XML Schema 优于DTD的地方:

  1. XML Schema 可针对未来的需求进行扩展
  2. XML Schema 更完善,功能更强大
  3. XML Schema 基于 XML 编写
  4. XML Schema 支持数据类型
  5. XML Schema 支持命名空间

先来说说xml文档的schema约束,它定义了xml文档的结构,内容和语法,包括元素和属性、关系的结构以及数据类型等。

有以下几点需要遵循:

  1. 所有的标签和属性都需要Schema来定义。(schema本身由w3c来定义)。

  2. 所有的schema文件都需要以个ID,这里我们称之为 namespace,其值时一个url,通常是这个xml的xsd文件的地址。

  3. namespace值由 targetNamespace 属性来指定

  4. 引入一个schema约束,使用属性xmlns,属性值即为对应schema文件的命名空间 nameSpace。

  5. 如果引入的schema非w3c组织定义的,必须指定schema文件的位置,schema文件的位置由 schemaLocation来指定。

  6. 引入多个schema文件需要使用别名。别名形式如下: xmlns:alias。

3.配置文件的详细解读

标签 说明
xmlns xml NameSpace : xml文件命名空间
xsi xml schema instance : xml Schema 实例
xsi:schemaLocation 指定命名空间 + Schema文件的位置
xmlns:alias xmlns:alias : 命名空间的别名
  1. 声明默认的名称空间(xmlns="http://www.springframework.org/schema/beans"

  2. 声明XML Schema实例名称空间(http://www.w3.o

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值