首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring 自定義 XML 標簽開發全流程

     編輯:Java 綜合教學

Spring 自定義 XML 標簽開發全流程

Spring 允許通過 Namespace 擴展定義專屬 XML 標簽,將複雜 Bean 定義簡化為語義化標簽。本文完整演示從 XSD 定義到 NamespaceHandler、BeanDefinitionParser 的實現全過程。

核心組件

  1. XSD Schema:定義標簽結構、屬性、類型約束;
  2. META-INF/spring.schemas:將網絡 XSD 映射到本地 classpath,避免啟動時下載;
  3. META-INF/spring.handlers:映射 namespace URI 到 NamespaceHandler 實現類;
  4. NamespaceHandler:註冊各標簽對應的 BeanDefinitionParser;
  5. BeanDefinitionParser:解析 DOM 元素,構建 BeanDefinition 註冊到容器。

實戰步驟

1. 定義 XSD (META-INF/test.xsd)

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="https://www.w3.org/2001/XMLSchema"
    targetNamespace="https://test.hatter.me/schema/test"
    xmlns="https://test.hatter.me/schema/test"
    elementFormDefault="qualified">
    <xsd:element name="custom">
        <xsd:complexType>
            <xsd:attribute name="id" type="xsd:ID"/>
            <xsd:attribute name="name" type="xsd:string"/>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

2. spring.schemas

http\://test.hatter.me/schema/test/test.xsd=META-INF/test.xsd

3. spring.handlers

http\://test.hatter.me/schema/test=me.hatter.test.TestNamespaceHandler

4. NamespaceHandler

public class TestNamespaceHandler extends NamespaceHandlerSupport {
    @Override public void init() {
        registerBeanDefinitionParser("custom", new TestCustomBeanDefinitionParser());
    }
}

5. BeanDefinitionParser

public class TestCustomBeanDefinitionParser implements BeanDefinitionParser {
    @Override public BeanDefinition parse(Element element, ParserContext ctx) {
        String id = element.getAttribute("id");
        String name = element.getAttribute("name");
        RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
        bd.getPropertyValues().addPropertyValue("name", name);
        ctx.getRegistry().registerBeanDefinition(id, bd);
        return bd;
    }
}

6. 使用自定義標簽

<beans xmlns:test="https://test.hatter.me/schema/test"
    xsi:schemaLocation="...
    https://test.hatter.me/schema/test https://test.hatter.me/schema/test/test.xsd">
    <test:custom id="testCustom" name="this is a test custom tag"/>
</beans>

驗證

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:me/hatter/test/main/test.xml");
System.out.println(ctx.getBean("testCustom")); // TestBean[name=this is a test custom tag]

適用場景

  • 基礎設施組件統一配置(如數據源、緩存、消息隊列);
  • 領域特定語言(DSL)簡化業務配置;
  • 框架擴展點對外暴露簡潔配置接口。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved