spring frameworkspring 整合使用

在Spring中自定义xml标签并解析

2022-05-06  本文已影响0人  养一只tom猫

首先可以从源码看到,Spring在加载xml时,会加载META-INF文件夹下的Spring.schemas与Spring.handlers文件。


image.png
image.png

Spring.schemas文件是配置xsd/dtd的
Spring.handlers才是配置对应命名空间走哪个处理器,处理器需要继承NamespaceHandlerSupport类,spring在解析的时候会调用处理器的init方法,在init方法中,我们需要注册解析器,解析器需要继承AbstractSingleBeanDefinitionParser类,在doParse方法中进行解析逻辑。

解析实体

public class User {

    private String username;

    private String password;

        get\set....

解析类

public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

    @Override
    protected Class<?> getBeanClass(Element element) {
        return User.class;
    }

    @Override
    protected void doParse(Element element, BeanDefinitionBuilder builder) {
        String username = element.getAttribute("username");
        String password = element.getAttribute("password");

        if (StringUtils.hasText(username)) {
            builder.addPropertyValue("username", username);
        }
        if (StringUtils.hasText(password)) {
            builder.addPropertyValue("password", password);
        }
    }
}

处理器

public class UserNamespaceHandler extends NamespaceHandlerSupport {

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

Spring.handlers

http\://www.jj.com/schema/jj=com.xiangjunjie.customize.tag.UserNamespaceHandler

Spring.schemas

http\://www.jj.com/schema/jj.xsd=META-INF/jj.xsd

jj.xsd

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:tns="http://www.jj.com/schema/jj"
        targetNamespace="http://www.jj.com/schema/jj"
        elementFormDefault="qualified">
    <element name="user">
        <complexType>
            <attribute name="id" type="string"/>
            <attribute name="username" type="string"/>
            <attribute name="password" type="string"/>
        </complexType>
    </element>

</schema>

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jj="http://www.jj.com/schema/jj"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.jj.com/schema/jj http://www.jj.com/schema/jj.xsd"
>

    <jj:user id="user" username="JunJie" password="123456"/>
</beans>
image.png
上一篇 下一篇

猜你喜欢

热点阅读