Spring源码-自定义标签
2022/8/29 1:24:01
本文主要是介绍Spring源码-自定义标签,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、新建实体类
public class User implements Serializable { private String id; private String name; private Integer age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { final StringBuffer sb = new StringBuffer("User{"); sb.append("id='").append(id).append('\''); sb.append(", name='").append(name).append('\''); sb.append(", age=").append(age); sb.append('}'); return sb.toString(); } }
二、新建xsd文件
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.myself.com/schema/user" xmlns:tns="http://www.myself.com/schema/user" elementFormDefault="qualified"> <element name="user"> <complexType> <attribute name ="id" type = "string"/> <attribute name ="name" type = "string"/> <attribute name ="age" type = "integer"/> </complexType> </element> </schema>
三、新建NamespaceHandler和BeanDefinitionParser
public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { @Override protected Class<?> getBeanClass(Element element) { return User.class; } @Override protected void doParse(Element element, BeanDefinitionBuilder builder) { if (element.hasAttribute("id")) { builder.addPropertyValue("id", element.getAttribute("id")); } if (element.hasAttribute("name")) { builder.addPropertyValue("name", element.getAttribute("name")); } if (element.hasAttribute("age")) { builder.addPropertyValue("age", element.getAttribute("age")); } } } public class UserNamespaceHandler extends NamespaceHandlerSupport { @Override public void init() { registerBeanDefinitionParser("user", new UserBeanDefinitionParser ()); } }
四、在resources目录下建立META-INF目录并新建spring.handlers和spring.schemas
spring.handlers
http\://www.myself.com/schema/user=selftag.UserNamespaceHandler
spring.schemas
http\://www.myself.com/schema/user.xsd=META-INF/user.xsd
五、使用
在app-test.xml文件的beans标签中加入
xmlns:aaa="http://www.myself.com/schema/user" http://www.myself.com/schema/user http://www.myself.com/schema/user.xsd
bean定义
<aaa:user name="李四" id="123" age="45"></aaa:user>
运行
ApplicationContext applicationContext = new MyClassPathApplicationContext("classpath:app-${user}.xml"); User user = applicationContext.getBean(User.class); System.out.println(user);
这篇关于Spring源码-自定义标签的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-27OpenFeign服务间调用学习入门
- 2024-12-27OpenFeign服务间调用学习入门
- 2024-12-27OpenFeign学习入门:轻松掌握微服务通信
- 2024-12-27OpenFeign学习入门:轻松掌握微服务间的HTTP请求
- 2024-12-27JDK17新特性学习入门:简洁教程带你轻松上手
- 2024-12-27JMeter传递token学习入门教程
- 2024-12-27JMeter压测学习入门指南
- 2024-12-27JWT单点登录学习入门指南
- 2024-12-27JWT单点登录原理学习入门
- 2024-12-27JWT单点登录原理学习入门