spring5 自定义脚本开发步骤
1 定义bean,
public class User {
private String id;
private String userName;
private String email;
private String password;
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;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2 自定义 BeanDefinitionParser,继承 AbstractSingleBeanDefinitionParser
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
protected Class<?> getBeanClass(Element element){
return User.class;
}
protected void doParse(Element element, BeanDefinitionBuilder builder){
String userName = element.getAttribute("userName");
String email = element.getAttribute("email");
String password = element.getAttribute("password");
String id = element.getAttribute("id");
if (StringUtils.hasText(userName)){
builder.addPropertyValue("userName", userName);
}
if (StringUtils.hasText(email)){
builder.addPropertyValue("email", email);
}
if (StringUtils.hasText(password)){
builder.addPropertyValue("password", password);
}
if (StringUtils.hasText(id)){
builder.addPropertyValue("id", id);
}
}
}
3 定义 NameSpaceHandler, 继承 NamespaceHandlerSupport,
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
public class UserNameSpaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("user", new UserBeanDefinitionParser());
}
}
4 自定义配置文件,在resource/META-INF 目录下,新建spring.handlers , spring.schemas , user.xsd 文件。
spring.handlers 文件内容如下:
http\://www.gientech.com/schema/user=com.gientech.selftag.UserNameSpaceHandler
spring.schemas 文件内容如下:
http\://www.gientech.com/schema/user.xsd=META-INF/user.xsd
spring.xsd 文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.gientech.com/schema/user"
xmlns:tns="http://www.gientech.com/schema/user"
elementFormDefault="qualified">
<element name="user">
<complexType>
<attribute name="id" type="string"></attribute>
<attribute name="userName" type="string"></attribute>
<attribute name="email" type="string"></attribute>
<attribute name="password" type="string"></attribute>
</complexType>
</element>
</schema>
5 spring-content.xml 引入命名空间,使用新标签配置bean
6 启动Spring 项目, 获取bean的值,
7 打印结果如下:
自定义变迁开发完成,按照步骤可正确开发自定义标签。