Spring配置文件中的<beans>标签

来源:互联网 发布:数据权限清理方案 编辑:程序博客网 时间:2024/05/14 09:04

以下是我在学习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:aop="http://www.springframework.org/schema/aop"        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-4.3.xsd            http://www.springframework.org/schema/aop            http://www.springframework.org/schema/aop/spring-aop.xsd">    <context:component-scan        base-package="com.bean.service,com.bean.aop"        annotation-config="true">    </context:component-scan>    <aop:aspectj-autoproxy proxy-target-class="true" /></beans>

直接用着没什么问题,但 beans 标签中的一大串网址还是比较令人在意的,所以整理以下 beans 标签中各个属性的意思,方便理解。

beans
配置文件的根节点,其中可以包含bean元素和其他元素。
附带beans标签的定义:http://blog.csdn.net/tanga842428/article/details/53086086

Element : beans
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.

Content Model : (description?, (import | alias | bean | namespace:uri=”##other”), beans)

xmlns
XML 命名空间(XML Namespaces)
为了避免Spring的beans标签与其他文件中的beans标签重名而导致冲突,作用类似于一个前缀。
用于标示命名空间的地址一般不会被解析器用于查找信息。其惟一的作用是赋予命名空间一个惟一的名称。不过,很多公司常常会作为指针来使用命名空间指向实际存在的网页,这个网页包含关于命名空间的信息。

Spring中xmlns指向的地址就包含了命名空间的信息,当改动xmlns中的网址时,编译会报错。
Exception in thread “main” org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 12 in XML document from class path resource [AspectJ.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 63; cvc-elt.1: 找不到元素 ‘beans’ 的声明。

详细介绍与简单举例:http://www.w3school.com.cn/xml/xml_namespaces.asp

xmlns:xsi
xmlns标注了文件的默认命名空间,在使用时不需前缀就可以使用其中的标签。
而xmlns:xsi则指该文件使用的其他命名空间,名称为xsi,在使用其中的标签时要加上xsi:的前缀。
冒号后的命名空间不是固定的,可以变更。xmlns的语法为:xmlns:namespace-prefix=”namespaceURI”。

推荐一篇更详细介绍xmlns的文章:https://yq.aliyun.com/articles/40353

xsi:schemaLocation
XML Schema提供了两个在实例文档中使用的特殊属性,用于指出模式文档的位置。这两个属性是:xsi:schemaLocation和xsi:noNamespaceSchemaLocation,前者用于声明了目标名称空间的模式文档,后者用于没有目标名称空间的模式文档,它们通常在实例文档中使用。

xsi:schemaLocation属性的值由一个URI引用对组成,两个URI之间以空白符分隔。第一个URI是名称空间的名字,第二个URI给出模式文档的位置,模式处理器将从这个位置读取模式文档,该模式文档的目标名称空间必须与第一个URI相匹配。
xsi:noNamespaceSchemaLocation属性的值为模式文档文件的地址,不需要命名空间,所以使用成对的值。

关于Schema的知识,可以参考:http://blog.csdn.net/wanghuan203/article/details/9203621

0 0