文章内容参考了《Spring源码深度解析》一书。自己照着书中内容做了一遍,不懂的地方以及采坑的地方会在文中记录。

推荐一篇post,关于Spring配置文件的命名空间:

https://www.cnblogs.com/gonjan-blog/p/6637106.html

我们暂时只是知道使用Spring的常规标签,加个bean,事务,Aop等等。随着满足业务的需求,同时降低程序员的工作量,我们有时需要自己定制一些标签。话补多少,下面进入主题。

自定义标签的使用

扩展Spring自定义标签大致需要如下几步:(把大象装冰箱,需要三步,开门,放,关门。。。)

1.创建需要扩展的组件

2.定义XSD文件描述组件内容

3.创建一个文件,实现BeanDefinitionParser接口,用来解析XSD文件中的定义和组件定义

4.创建Handler文件,扩展字NamespaceHandlerSupport,目的是将组件注册到Spring容器

5.编写Spring.handlers和Spring.schemas文件

上述,五点看完了,我最开始时一头雾水,这是什么啊?别着急,跟哥往下走。下面有好东西,保证不打晕你。

例子:

1.创建POJO,接收配置文件

 package test.customtag;

 public class User {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

2.定义一个XSD文件描述组件内容

src/main/resources/META-INF/user.xsd

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

描述了一个targetNamespace,并且创建了一个element user2。里面有三个attribute。主要是为了验证Spring配置文件中的自定义格式。再进一步解释,就是,Spring位置文件中使用的user2自定义标签中,属性只能是上面的三种,有其他的属性的话,就会报错。

网上有人说element ,complexType等等这些标签要用XSD开头的标签,但是我这里没有用也能成功的执行,我猜测可能是spring的版本问题。(我这个猜测没有依据)

大家对这个XSD可能会有疑问,不要担心。推荐一篇post,里面讲解的很好,地址放在文章开头那里。

3.创建文件,实现BeanDefinitionParser接口,用来解析XSD文件中的定义和组件定义

 package test.customtag;

 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 { @SuppressWarnings("rawtypes")
protected Class getBeanClass(Element element) {
return User.class;
} protected void doParse(Element element, BeanDefinitionBuilder bean) {
String userName = element.getAttribute("userName");
String email = element.getAttribute("email");
if (StringUtils.hasText(userName)) {
bean.addPropertyValue("userName", userName);
}
if (StringUtils.hasText(email)){
bean.addPropertyValue("email", email);
} }
}

上文,虽说是继承了AbstractSingleBeanDefinitionParser ,但根本上来说,是实现了BeanDefinitionParser接口。

4.创建Handler文件,扩展自NamespaceHandlerSupport,目的是将组件注册到Spring容器中。

 package test.customtag;

 import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

 public class MyNamespaceHandler extends NamespaceHandlerSupport {

     public void init() {

         registerBeanDefinitionParser("user2", new UserBeanDefinitionParser());
} }

5.编写Spring.handlers和Spring.schemas文件

路径:src/main/resources/META-INF/Spring.handlers

 http\://www.example.org/schema/user=test.customtag.MyNamespaceHandler

路径:src/main/resources/META-INF/Spring.schemas

 http\://www.example.org/schema/user.xsd=META-INF/user.xsd

\ 是转义字符的概念。

6.创建测试配置文件

路径:src/main/resources/test.xml

 <?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:myname2="http://www.example.org/schema/user"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.example.org/schema/user http://www.example.org/schema/user.xsd"> <myname2:user2 id = "testbean" userName = "lee" email = "bbb"/>
</beans>

在第4行这里引入了myname2对应的命名空间,它会到第六行(http://www.example.org/schema/user.xsd)找到对应XSD文件进行check。第六行的user.xsd文件的位置,到步骤5里的Spring.schemas里去参照。

在这里说明一下自己遇到的疑问:第八行,自己eclipse报了红叉,信息如下:

Multiple annotations found at this line:
    - cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'myname2:user2'.
    - schema_reference.4: Failed to read schema document 'http://www.example.org/schema/user.xsd', because 1) could not find the
     document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

但是,我没有解决它,直接执行第6步的代码,最后成功执行了,搞不懂原因。

6.测试。

 package test.customtag;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Tst {
public static void main(String[] args) {
ApplicationContext beans=new ClassPathXmlApplicationContext("classpath:test.xml");
User user=(User)beans.getBean("testbean");
System.out.println("username:"+user.getUserName()+" "+"email:"+user.getEmail());
}
}

文章记录的不是特别的详细,有一些知识点没有全面的记录。但是,跟着一步步做,Spring自定义标签的实现,应该是没有问题了。稍后,有时间,会记录Sping源码中,关于自定义标签解析的部分。与君共勉。

Spring——使用自定义标签的更多相关文章

  1. Spring的自定义标签

    当Spring拿到一个元素时首先要做的是根据命名空间进行解析,如果是默认的命名空间,则使用parseDefaultElement方法进行元素解析,否则使用parseCustom Element方法进行 ...

  2. 基于Spring开发——自定义标签及其解析

    1. XML Schema 1.1 最简单的标签 一个最简单的标签,形式如: <bf:head-routing key="1" value="1" to= ...

  3. spring thymeleaf 自定义标签

    概述 thymeleaf2.1.5自定义标签及自定义属性案例,类似于JSP中的自定义JSTL标签 详细 代码下载:http://www.demodashi.com/demo/10495.html 一. ...

  4. Spring IoC 自定义标签解析

    前言 本系列全部基于 Spring 5.2.2.BUILD-SNAPSHOT 版本.因为 Spring 整个体系太过于庞大,所以只会进行关键部分的源码解析. 本篇文章主要介绍 Spring IoC 容 ...

  5. Spring源码学习-容器BeanFactory(四) BeanDefinition的创建-自定义标签的解析.md

    写在前面 上文Spring源码学习-容器BeanFactory(三) BeanDefinition的创建-解析Spring的默认标签对Spring默认标签的解析做了详解,在xml元素的解析中,Spri ...

  6. Spring 系列教程之自定义标签的解析

    Spring 系列教程之自定义标签的解析 在之前的章节中,我们提到了在 Spring 中存在默认标签与自定义标签两种,而在上一章节中我们分析了 Spring 中对默认标签的解析过程,相信大家一定已经有 ...

  7. dubbo源码学习(二) : spring 自定义标签

    做dubbo的配置时很容易发现,dubbo有一套自己的标签,提供给开发者配置,其实每一个标签对应着一个 实体,在容器启动的时候,dubbo会对所有的配置进行解析然后将解析后的内容设置到实体里,最终du ...

  8. 死磕Spring之IoC篇 - 解析自定义标签(XML 文件)

    该系列文章是本人在学习 Spring 的过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring 源码分析 GitHub 地址 进行阅读 Spring 版本:5.1. ...

  9. Spring 源码(4)在Spring配置文件中自定义标签如何实现?

    Spring 配置文件自定义标签的前置条件 在上一篇文章https://www.cnblogs.com/redwinter/p/16165274.html Spring BeanFactory的创建过 ...

随机推荐

  1. day29 socketsever ftp功能简单讲解

    今日所学 一.ftp上传简单实例 二.socketsever的固定用法 三.验证合法性连接 1.ftp上传实例 这个题目是我们现在网络编程比较基础一点的题目 下面我们只写简单上传的代码 上传服务端的代 ...

  2. selenium登录界面,创建表单并填写提交

    #! python3 # -*- coding:utf8 -*- # https://selenium-python.readthedocs.io/api.html#selenium.webdrive ...

  3. C++的string类型和继承C语言风格的字符串的区别与注意事项

    1.尽可能地在C++程序中使用string,不要使用继承而来的C语言风格的字符串,会出现许多安全问题. 2.C语言的字符串风格,是以空字符结束的,在C++的头文件cstring中定义了C语言风格的字符 ...

  4. 50个常用的Linux命令

    1.tar tar -xvf archive_name.tar  解压文件 tar -cvf archive_name.tar file 把文件file压缩成archive_name.tar tar ...

  5. python获取代理IP

    利用requests库获取代理,用Beautiful库解析网页筛选ip # -*- coding: utf- -*- import requests from bs4 import Beautiful ...

  6. 栈回溯简单实现(x86)

    0x01  栈简介  首先局部变量的分配释放是通过调整栈指针实现的,栈为函数调用和定义局部变量提供了一块简单易用的空间,定义在栈上的变量不必考虑内存申请和释放.只要调整栈指针就可以分配和释放内存.   ...

  7. mybatis学习(五)----实现关联表查询

    一.一对一的表查询 查询班级表中班级号为1的对应的记录(包括教师的具体信息) 1.首先建立数据表 数据表class和techear,class表中只有一个外键techear_id,sql脚本如下: C ...

  8. IEDA中彻底删除项目

    删除项目一向比较奇葩,因为当你点击到 该项目名称-->右键 时,并没有 delete 选项,导致我们不知道怎么删除,查找多方文档,得到以下解决: (1)将鼠标移到要删除的 项目名称 上,单击并按 ...

  9. phpexcel 的使用

    首先到phpexcel官网上下载最新的phpexcel类,下周解压缩一个classes文件夹,里面包含了PHPExcel.php和PHPExcel的文件夹,这个类文件和文件夹是我们需要的,把class ...

  10. promise、async和await之执行顺序

    async function async1(){ console.log('async1 start') await async2() console.log('async1 end') } asyn ...