【Spring学习】Spring自定义标签详细步骤

前言

Spring中除了http://www.springframework.org/schema/beans命名空间提供了默认标签,其他的命名空间的标签均为自定义标签。

为了更好的理解自定义标签在Spring中是如何加载与注册的,我们现在手动写一个自定义标签。

一、自定义标签步骤

最终目录结构:
在这里插入图片描述

1、定义属性POJO

package com.cms.customtag;

import lombok.Data;

/**
 * @author: cms
 * @date: 2023/3/2 9:46 PM
 * @description: 定义自定义标签的属性。
 */
@Data
public class User {
    private String userName;

    private String email;
}

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

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.cms.com/schema/user"
        elementFormDefault="qualified" >

    <xsd:element name="user">
            <xsd:complexType>
                <xsd:attribute name="id" type="xsd:string"/>
                <xsd:attribute name="userName" type="xsd:string"/>
                <xsd:attribute name="email" type="xsd:string"/>
            </xsd:complexType>
    </xsd:element>

</xsd:schema>

3、定义标签解析器

package com.cms.customtag;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

/**
 * @author: cms
 * @date: 2023/3/2 10:02 PM
 * @description: 【创建】命名空间解析器。实现 BeanDefinitionParser 接口,用来解析 XSD 文件中的定义和组件定义。
 */
public class UserBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {

    /**
     *  Element对应的类
     */
    @Override
    protected Class getBeanClass (Element element) {
        return User.class;
    }

    /**
     *  功能描述:从element中解析并提取对应的元素
     */
    @Override
    public void doParse (Element element, BeanDefinitionBuilder bean) {
        String userName = element.getAttribute("userName");
        String email    = element.getAttribute("email");

        // 将提取的数据放入到 BeanDefinitionBuilder中,待到完成所有 bean 的解析后统一注册到beanFactory 中
        if(StringUtils.hasText(userName)) {
            bean.addPropertyValue("userName", userName);
        }
        if(StringUtils.hasText(email)) {
            bean.addPropertyValue("email", email);
        }
    }
}

4、注册标签解析器

package com.cms.customtag;

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

/**
 * @author: cms
 * @date: 2023/3/2 10:13 PM
 * @description: 【注册】命名空间解析器。
 */
public class MyNamespaceHandler extends NamespaceHandlerSupport {

    public void init () {
        // 'user'作为自定义标签的名称。 格式:<user id="" />
        registerBeanDefinitionParser("user", new UserBeanDefinitionParser());
    }
}

5、定义spring.handlers和spring.schemas文件

编写 spring.handlers 和 spring.schemas 文件,默认位置是在工程的/META-INF/文件夹下,当然,你可以通过 Spring 的扩展或者修改源码的方式改变路径。

spring.handlers配置命名空间与命名空间解析器的映射关系:

http\://www.cms.com/schema/user=com.cms.customtag.MyNamespaceHandler

spring.schemas配置xsd文件的真实位置:

http\://www.cms.com/schema/user.xsd=com/cms/customtag/user.xsd

到这里,自定义的配置就结束了,而 Spring 加载自定义的大致流程是遇到自定义标签然后就去 spring.handlers 和 spring.schemas 中去找对应的 handler 和XSD,默认位置是/META-INF/下,进而有找到对应的 handler 以及解析元素的 Parser,从而完成了整个自定义元素的解析。也就是说自定义与 Spring 中默认的标准配置不同在于 Spring 将自定义标签解析的工作委托给了用户去实现。

6、user.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:myname="http://www.cms.com/schema/user"
       xsi:schemaLocation=
               "http://www.cms.com/schema/user http://www.cms.com/schema/user.xsd
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--mybame是命名空间http://www.cms.com/schema/user的别名-->
    <myname:user id="userBean" userName="咖啡" email="coffee.qq.com"/>

</beans>

7、测试类

package com.cms.customtag;

import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author: cms
 * @date: 2023/3/3 3:19 PM
 * @description: xxx
 */
public class CustomTagTest {

    @Test
    public void test () {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/cms/customtag/user.xml");
        User user = (User) context.getBean("userBean");
        System.out.println(user.getUserName() + "," + user.getEmail());
    }
}

结果:

16:09:05.397 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2b6856dd
16:09:05.499 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [com/cms/customtag/user.xml]
16:09:05.512 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userBean'
咖啡,coffee.qq.com

Process finished with exit code 0

二、仓库位置

【Gitee】spring-xml-demo模块

总结

待补充。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@来杯咖啡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值