spring扩展

文章目录

spring除了可以解析自定的标签外,也可以解析用户自定义的标签。解析自定义标签需要添加一些扩展。下面以一个实例展示这个过程。

1.在resources/META-INF目录下新建文件spring-test.xsd

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.test.com/schema/user">
<xs:element name="user">
<xs:complexType>
<xs:attribute name="id" type="xs:string"></xs:attribute>
<xs:attribute name="userName" type="xs:string"></xs:attribute>
<xs:attribute name="email" type="xs:string"></xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>

2.在resource/META-INF目录下创建spring.schema文件,并添加以下内容。

http\://www.test.com/schema/user.xsd=META-INF/spring-test.xsd

3.创建自定义bean解析器类UserBeanDefinitionParser,该类需要继承AbstractSingleBeanDefinitionParser

public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected Class<?> getBeanClass(Element element) {
return User.class;
}
// 从element中解析并提取相应的元素
@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.创建自定义namespace处理器类MyNamespaceHandler,该类需要继承NamespaceHandlerSupport

public class MyNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("user", new UserBeanDefinitionParser());
}
}

5.定义一个实体类

@Data
public class User {

private String id;
private String userName;
private String email;

@Override
public String toString() {
return this.getUserName() + "--" + this.getEmail();
}
}

6.创建一个xml文件,beans3.xml,使用自定义标签定义bean

<?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:context="http://www.springframework.org/schema/context"
xmlns:myname="http://www.test.com/schema/user"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.test.com/schema/user
http://www.test.com/schema/user.xsd">

<myname:user id="testbean" userName="aaa" email="bbb"/>
</beans>

7.定义一个测试类,测试能否成功加载该bean

public class TestApp {
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans3.xml"));
User u1 = (User)factory.getBean("testbean");
System.out.println(u1);
}
}
  1. 输出结果
aaa--bbbf