spring框架的XML扩展特性:让spring加载和解析你自定义的XML文件

Spring框架从2.0版本开始,提供了基于Schema风格的XML扩展机制,允许开发者扩展最基本的spring配置文件(一般是classpath下的spring.xml)。试想一下,如果我们直接在spring.xml中加入一个自定义标签<mytag id="aty"></matag>,会发生什么呢?spring框架启动的时候会报错,因为spring根本不认识我们自定义的<mytag>,这样对spring.xml的校验就会失败,最终结果就是框架不能启动。有什么方法,能够让spring认识并加载解析我们自定义的<mytag>呢?这就是spring提供的xml扩展机制。我们可以在spring.xml中加入自己的标签,之后spring会帮我们解析并纳入自己的管理范围内,这也就是说我们扩展了spring的功能。

现在我们来看下怎么实现这个功能,可以参考spring帮助文档中的extensible-xml.html。我们知道如果在需要在spring.xml中配置数据源,需要进行如下的配置:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">         
  2.     <property name="driverClassName" value="com.mysql.jdbc.Driver" />        
  3.     <property name="url" value="jdbc:mysql://localhost:3309/sampledb" />        
  4.     <property name="username" value="root" />        
  5.     <property name="password" value="1234" />        
  6. </bean>   
这种方式配置虽然也比较简单,但是有一个缺点:使用<property>标签不够明显,不如元素属性那么直接。现在我们希望在spring.xml中做如下的配置,就能够完成数据源的配置。

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <aty:datasource id="myDataSourcce" url="jdbc:mysql://localhost:3309/demodb" userName="root" password="root" />  
这种方式比较直接,配置不容易出错。如果让spring能够解析这个标签,需要4步。

1、提供一个xsd文件,负责对xml的标签<datasource>进行校验

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <xsd:schema xmlns="http://www.aty.com/schema/aty" xmlns:xsd="http://www.w3.org/2001/XMLSchema"  
  3.     xmlns:beans="http://www.springframework.org/schema/beans"  
  4.     targetNamespace="http://www.aty.com/schema/aty" elementFormDefault="qualified"  
  5.     attributeFormDefault="unqualified">  
  6.   
  7.     <xsd:import namespace="http://www.springframework.org/schema/beans" />  
  8.   
  9.     <xsd:element name="datasource">  
  10.         <xsd:complexType>  
  11.             <xsd:complexContent>  
  12.                 <xsd:extension base="beans:identifiedType">  
  13.                     <xsd:attribute name="url" type="xsd:string" use="required" />  
  14.                     <xsd:attribute name="userName" type="xsd:string" use="required" />  
  15.                     <xsd:attribute name="password" type="xsd:string" use="required" />  
  16.                 </xsd:extension>  
  17.             </xsd:complexContent>  
  18.         </xsd:complexType>  
  19.     </xsd:element>  
  20.   
  21. </xsd:schema>  

2、定义一个BeanDefinitionParser负责解析xml,并将必要的信息放入spring中

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package net.aty.custom.define;  
  2.   
  3. import net.aty.custom.cfg.DataSourceInfo;  
  4.   
  5. import org.springframework.beans.factory.config.BeanDefinition;  
  6. import org.springframework.beans.factory.config.BeanDefinitionHolder;  
  7. import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;  
  8. import org.springframework.beans.factory.support.RootBeanDefinition;  
  9. import org.springframework.beans.factory.xml.BeanDefinitionParser;  
  10. import org.springframework.beans.factory.xml.ParserContext;  
  11. import org.w3c.dom.Element;  
  12.   
  13. public class DatasourceBeanDefinitionParser implements BeanDefinitionParser  
  14. {  
  15.     public BeanDefinition parse(Element element, ParserContext context)  
  16.     {  
  17.         RootBeanDefinition def = new RootBeanDefinition();  
  18.   
  19.         // 设置Bean Class  
  20.         def.setBeanClass(DataSourceInfo.class);  
  21.   
  22.         // 注册ID属性  
  23.         String id = element.getAttribute("id");  
  24.         BeanDefinitionHolder idHolder = new BeanDefinitionHolder(def, id);  
  25.         BeanDefinitionReaderUtils.registerBeanDefinition(idHolder,  
  26.                 context.getRegistry());  
  27.   
  28.         // 注册属性  
  29.         String url = element.getAttribute("url");  
  30.         String userName = element.getAttribute("userName");  
  31.         String password = element.getAttribute("password");  
  32.   
  33.         BeanDefinitionHolder urlHolder = new BeanDefinitionHolder(def, url);  
  34.         BeanDefinitionHolder userNameHolder = new BeanDefinitionHolder(def,  
  35.                 userName);  
  36.         BeanDefinitionHolder passwordHolder = new BeanDefinitionHolder(def,  
  37.                 password);  
  38.   
  39.         BeanDefinitionReaderUtils.registerBeanDefinition(urlHolder,  
  40.                 context.getRegistry());  
  41.         BeanDefinitionReaderUtils.registerBeanDefinition(userNameHolder,  
  42.                 context.getRegistry());  
  43.         BeanDefinitionReaderUtils.registerBeanDefinition(passwordHolder,  
  44.                 context.getRegistry());  
  45.   
  46.         def.getPropertyValues().addPropertyValue("url", url);  
  47.         def.getPropertyValues().addPropertyValue("userName", userName);  
  48.         def.getPropertyValues().addPropertyValue("password", password);  
  49.   
  50.         return def;  
  51.     }  
  52. }  
该类的功能:设置相关的BeanClass,解析了对应的xsd文件,并将解析的内容注册到上下文中,同时返回一个BeanDefinition对象(BeanDefinition是Spring的bean定义,提供了bean部分的操作方法,如isSingleton()、isLazyInit()等)。注意:id属性是一个默认的属性,可以不在xsd文件中描述,但是需要注册它,否则将无法通过getBean方法获取标签定义的bean,也无法被其他bean引用。


3、定义个NamespaceHandler,由sping框架的调用入口。这也是我们自定义xml解析的入口

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package net.aty.custom.define;  
  2.   
  3. import org.springframework.beans.factory.xml.NamespaceHandlerSupport;  
  4.   
  5. public class DatasourceNamespaceHandlerSupport extends NamespaceHandlerSupport  
  6. {  
  7.     @Override  
  8.     public void init()  
  9.     {  
  10.         registerBeanDefinitionParser("datasource",  
  11.                 new DatasourceBeanDefinitionParser());  
  12.     }  
  13. }  

4、配置schema和handler

Spring没那么聪明,它无法知道我们在什么地方定义了哪些扩展标签,这些标签将被谁解析,怎么解析。这个过程要我们通过一些配置文件来告知Spring知道,它们就是spring.handlers和spring.schemas,它们放在META-INF目录中。Spring.jar的META-INF目录中也有同名的文件,它们的文件内容基本上是相似的,而Spring在执行过程中,如果发现其他jar文件的META-INF文件夹中包含有这两个文件,Spring将会合并它们。

spring.handlers内容如下:

[plain]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. http\://www.aty.com/schema/aty=net.aty.custom.define.DatasourceNamespaceHandlerSupport  
spring.schemas内容如下:

[plain]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. http\://www.aty.com/schema/aty.xsd=aty.xsd  


我的工程目录结构如下图:



至此扩展xml完成,我们可以进行测试了。可以通过eclipse将spring_customDefine_xml工程导出成jar,然后再别的工程中进程测试即可。

测试工程的spring.xml配置如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:aty="http://www.aty.com/schema/aty"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  7.            http://www.aty.com/schema/aty  
  8.            http://www.aty.com/schema/aty.xsd">  
  9.   
  10.     <aty:datasource id="myDataSourcce" url="jdbc:mysql://localhost:3309/demodb" userName="root" password="root" />  
  11.   
  12. </beans>  

测试类代码如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import net.aty.custom.cfg.DataSourceInfo;  
  2.   
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  4.   
  5. public class TestMain  
  6. {  
  7.     private static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(  
  8.             "spring.xml");  
  9.   
  10.     public static void main(String[] args)  
  11.     {  
  12.         DataSourceInfo d = (DataSourceInfo) context.getBean("myDataSourcce");  
  13.         System.out.println(d);  
  14.     }  
  15.   
  16. }  

测试的工程目录结构如下:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值