spring与xml schema

本文从自定义spring配置文件入手,介绍了spring配置文件头的原理,和spring.schema、spring.handlers两个文件的作用。

下面是一个简单的spring配置文件。我们可以看到,xml文件的前几行这些配置,其实都是xml 结构的定义,通过引入这些定义,使xml文件中的标签可以正常被spring解析。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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">
    <context:annotation-config/>
</beans>

那么这些代码是什么含义?spring是如何解析这些配置文件的?我们能否轻松解析自定义的xml配置文件呢?本篇文章或许能够帮你解答疑惑。

1.XML文件头

xml文件的头部位置是用来对验证模式进行声明的,以保证文件的正确性。xml文件的验证模式常见的有两种,一种是DTD(文档类型定义)和XSD(XML Schema)。DTD因为其不可扩展、不支持命名空间等缺陷,逐渐被XSD所淘汰,目前主流框架如maven、spring等使用的xml配置文件的验证模式都是XSD模式,因此在此不再赘述DTD。

XSD是基于xml语法进行编写的验证文件,通过xsd文件,我们可以进行xml标签的自定义。XSD模式的优点在此不再赘述,网上有很多,总结下来,就是XSD模式更灵活、更兼容、更简单。

对XSD的使用,我们可以分为两部分,XSD的定义以及XSD的引用。

1.1 XSD的定义

所谓定义XSD,即定义一个xml文件的使用模式,这里面定义了以下内容:

  • xml文档中使用的标签元素
  • 标签元素对应的属性
  • 标签元素及其属性的类型
  • 标签元素的子元素,包括子元素的类型、数目、次序
  • 标签元素的默认类型和默认值

这个是spring-beans的xsd文件的一部分:

<!-- Top-level <beans> tag -->
	<xsd:element name="beans">
		<xsd:annotation>
			<xsd:documentation><![CDATA[
	Container for <bean> and other elements, typically the root element in the document.
	Allows the definition of default values for all nested bean definitions. May itself
	be nested for the purpose of defining a subset of beans with certain default values or
	to be registered only when certain profile(s) are active. Any such nested <beans> element
	must be declared as the last element in the document.
			]]></xsd:documentation>
		</xsd:annotation>
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="description" minOccurs="0"/>
				<xsd:choice minOccurs="0" maxOccurs="unbounded">
					<xsd:element ref="import"/>
					<xsd:element ref="alias"/>
					<xsd:element ref="bean"/>
					<xsd:any namespace="##other" processContents="strict" minOccurs="0" maxOccurs="unbounded"/>
				</xsd:choice>
				<xsd:element ref="beans" minOccurs="0" maxOccurs="unbounded"/>
			
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值