xmlns 属性,可以写在xml或者html的开始标签中,比如:
<beans xmlns=""></beans>
或者
<table xmlns=""></table >
它的名称是xml namespace,也就命名空间。
它的作用:
就拿spring来举例,如果你的spring需要配置spring的aop功能和事务tx功能,那么在spring配置文件的beans标签内部你肯定需要用到spring-aop、spring-tx、spring-context中的标签元素。
spring-aop、spring-tx、spring-context中包含哪些标签元素,这是在xsd文件中设定好的,同时也是为了校验配置文件的标签是否正确,比如http://www.springframework.org/schema/context/spring-context.xsd文件定义如下:
可以看到,其中就包含了component-scan标签元素,加入没有命名空间,那么配置内容就是如下:
<beans>
<component-scan base-package="com.home" />
</beans>
问题来了,如果存在其他比如它test.xsd文件中也存在component-scan标签元素,这样是不是就冲突了呢?
比如:
<beans>
<!-- spring-context.xsd -->
<component-scan base-package="com.home" />
<!-- test.xsd -->
<component-scan test="test" />
</beans>
所以,如果引入其他xsd定义中的标签,则需要分配命名空间。
如何使用:
先来一个spring配置的例子:
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
这里spring需要用到aop和事务tx的功能,他们的标签元素分别定义在spring-aop.xsd和spring-tx.xsd中。
1、xmlns指定引入的命名空间,比如上面引入了context、aop、tx。而xmlns="http://www.springframework.org/schema/beans"表示默认的命名空间是beans。
2、xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” 是默认写法,必须加上,后面才能用到xsi:schemaLocation。
3、xsi:schemaLocation属性指定命令空间的xsd文件路径,它的格式是
xsi:schemaLocation="键 值 键 值 键 值 "
键 值是成对出现的,键是比如 xmlns:aop="http://www.springframework.org/schema/aop"中的http://www.springframework.org/schema/aop,值是spring-aop.xsd的文件路径。
4、配置好xmlns:context和指定xsi:schemaLocation之后,就可以在<beans>
标签内部通过命名空间context来使用其标签元素,比如:
<!-- 开启注解 -->
<context:annotation-config />
其他命名空间也是一样的使用方法。
5、介绍下p空间,如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
xmlns:p不需要在xsi:schemaLocation中指定xsd文件路径,它是灵活配置属性名的意思。
比如:
<beans>
<bean id="test" p:password="123" p:clazz-ref="springTest" />
</beans>
说明:
配置 xmlns:p命名空间后,可以在标签内通过“p:属性名称=值”来灵活配置属性,属性名称需要对应到具体的属性名。如果属性名称中以“-ref”结尾,默认代表这个属性的值是一个类的映射。