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-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南