spring源码学习之自定义标签
自定义标签步骤:
1、创建xsd约束文件,一般/META-INE/文件夹下
2、创建java实体类
3、创建自定义标签解析器,实现AbstractSingleBeanDefinitionParser类
4、创建处理器,将解析器 绑定到handler处理器,继承NamespaceHandlerSupport
5、编写spring.handle 和spring.schemas文件/META-INE/文件夹下
6、编写bean的xml文件
7、进行测试
1、创建spring-test.xsd约束文件,一般/META-INE/文件夹下
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.spring.test.com/shema/user"
xmlns:tns="http://www.spring.test.com/shema/user"
elementFormDefault="qualified">
<element name="user" >
<complexType>
<attribute name="id" type="string"/>
<attribute name="userName" type="string"/>
<attribute name="email" type="string"/>
</complexType>
</element>
</schema>
2、创建java实体类
public class User {
private String userName;
private String email;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3、创建自定义标签解析器UserBeanDefinitionParser.java,实现AbstractSingleBeanDefinitionParser类
public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser{
@Override
protected Class<?> getBeanClass(Element element) {
return User.class;
}
@Override
protected void doParse(Element element, BeanDefinitionBuilder builder) {
String userName = element.getAttribute("userName");
String email = element.getAttribute("email");
if (StringUtils.hasText(userName)){
builder.addPropertyValue("userName",userName);
}
if (StringUtils.hasText(email)){
builder.addPropertyValue("email",email);
}
}
}
4、创建处理器UserBeanHandler .java,将解析器 绑定到handler处理器,继承NamespaceHandlerSupport
public class UserBeanHandler extends NamespaceHandlerSupport {
@Override
public void init() {
//此处可以定义多个标签处理器
registerBeanDefinitionParser("user",new UserBeanDefinitionParser());
}
}
5、编写spring.handle 和spring.schemas文件/META-INE/文件夹下
spring.handle
http\://www.spring.test.com/shema/user=com.golddishtech.phantom.web.CusBeanName.UserBeanHandler
spring.schemas
http\://www.spring.test.com/shema/user.xsd=META-INF/spring-test.xsd
6、编写bean的xml文件
<?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:mybean="http://www.spring.test.com/shema/user"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.spring.test.com/shema/user http://www.spring.test.com/shema/user.xsd">
<mybean:user id="userTest" userName="aaa" email="bbb"/>
</beans>
7、进行测试
public class TestBean {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("**/userbean.xml");
User user = (User) applicationContext.getBean("userTest");
System.out.println("userName="+user.getUserName()+"email="+user.getEmail());
}
}