假如我们有一个User类,现在需要通过自定义标签,把这个对象初始化到springApplicationContext中以便于注入使用。
- 新建User类
public class User { private String id; private String userName; private String email; public String getId() { return id; } public void setId(String id) { this.id = id; } 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; } }
- 增加xml定义文件 spring-user.xsd
<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.wjs.com/schema/user" targetNamespace="http://www.wjs.com/schema/user" elementFormDefault="qualified"> <xsd:element name="user"> <xsd:complexType> <xsd:attribute name="id" type="xsd:string" /> <xsd:attribute name="userName" type="xsd:string" /> <xsd:attribute name="email" type="xsd:string" /> </xsd:complexType> </xsd:element> </xsd:schema>
- 定义beanDefiniton类 获取xml中对应定义的属性
import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.util.StringUtils; import org.test.spirng.xml.bean.definition.User; import org.w3c.dom.Element; 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); } } }
- 定义namespaceHandler 处理xml 中对应的标签
import org.springframework.beans.factory.xml.NamespaceHandlerSupport; public class MyUserNamespaceHandler extends NamespaceHandlerSupport { @Override public void init() { registerBeanDefinitionParser("user",new UserBeanDefinitionParser()); } }
- 配置标签对应的处理类spring.handlers
http://www.wjs.com/schema/user=org.test.spirng.xml.bean.definition.definition.MyUserNamespaceHandler
- 配置标签描述文件 即xsd文件
http://www.wjs.com/schema/user.xsd=META-INF/spring-user.xsd
- 用法
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:myTag="http://www.wjs.com/schema/user" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.wjs.com/schema/user http://www.wjs.com/schema/user.xsd"> <myTag:user id="testBean" userName="name" email="wjs@163.com"/> <myTag:user id="testBean1" userName="name1" email="wjs@163.com"/> </beans>
整个工程的截图
工程代码见附件。(去掉pom里的parnet标签即可使用)
https://files.cnblogs.com/files/z-test/test-spirng-xml-bean-definition.rar