目录
1.2、BeanDefinitionParser 实现类、NamespaceHandlerSupport实现类
1.3、spring.handlers、spring.schemas文件
2.4、BeanDefintionParser的parse()方法
自定义标签的概念我们听起来可能很陌生,但是一提起事务相关的配置<tx:advice /> 、<aop:config> 没错这个就是我们所说的自定义标签的使用。下面我们通过一个例子来简单实现一个自定义标签的例子来熟悉一下自定义标签的用法,后面我们在对自定义标签的解析做源码上的分析。
1、自定义标签的
1.1、PO类、xsd文件
//普通的pojo类
public class User {
private String name;
private Integer age;
}
//xsd描述文件
// schema 中的targetNamespace、xmlns:tns为自定义的命名空间
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/schema/user"
xmlns:tns="http://www.example.org/schema/user" elementFormDefault="qualified">
<element name="user">
<complexType>
<attribute name ="id" type = "string"/>
<attribute name ="name" type = "string"/>
<attribute name ="age" type = "int"/>
</complexType>
</element>
</schema>
1.2、BeanDefinitionParser 实现类、NamespaceHandlerSupport实现类
/**
* 自定义的标签元素的解析处理类
* 通过注册到对应的命名空间上 遇到具体的自定义标签会通过该类进行解析
*/
public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected Class<?> getBeanClass(Element element) {
return User.class;
}
//具体的标签解析功能的实现
@Override
protected void doParse(Element element, BeanDefinitionBuilder builder) {
String name = element.getAttribute("name");
String ageStr = element.getAttribute("age");
if(StringUtils.hasText(name)){
builder.addPropertyValue("name",name);
}
if(StringUtils.hasText(ageStr)){
builder.addPropertyValue("age",Integer.parseInt(ageStr));
}
}
}
/**
* 自定义的命名空间处理器
* 在spring.handles会将命名空间和该类进行绑定 这样使用具体的命名空间来进行标签的解析
* 而命名空间使用的是注册的BeanDefinitionParser来进行具体的解析
*/
public class MyNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
//注册新的解析器 对应user标签 对于命名空间下的所有user标签使用UserBeanDefinitionParser进行解析
registerBeanDefinitionParser("user",new UserBeanDefinitionParser());
}
}
1.3、spring.handlers、spring.schemas文件
spring容器启动的时候会先加载spring.handlers、spring.schemas文件。
//spring.handlers
//将命名空间和对应的命名处理器做绑定,让spring根据不同的命名空间获取到其对应的命名处理器
//从而进行相应的解析处理
http\://www.example.org/schema/user=com.xiu.customer.MyNamespaceHandler
//spring.schemas
//将对应的命名空间的xsd文件和真实的xsd文件做绑定 用来做自定义标签的校验
//使自定义标签使用者按照规范去使用标签,而非随意的添加或者修改标签的属性
http\://www.example.org/schema/user.xs