1. 程式人生 > 實用技巧 >spring引入自定義名稱空間

spring引入自定義名稱空間

需要的寫的程式碼檔案:

程式碼:

FirstParser

public class FirstParser implements BeanDefinitionParser {

    private static final String ACTION = "say";
    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        String sayWord = element.getAttribute(ACTION);
        System.
out.println(sayWord); return null; } }


MyNamespaceHandler
public class MyNamespaceHandler extends NamespaceHandlerSupport  {

    @Override
    public void init() {
        this.registerBeanDefinitionParser("word", new FirstParser());
    }
}

customize.xsd

<?xml version="1.0" encoding="
UTF-8"?> <xsd:schema xmlns="http://www.shishi.com/myschema/customize" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:beans="http://www.springframework.org/schema/beans" targetNamespace="http://www.shishi.com/myschema/customize" elementFormDefault="qualified" attributeFormDefault="
unqualified"> <xsd:element name="word"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:attribute name="say" type="xsd:string" use="required" /> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:schema>

spring.handlers

http\://www.shishi.com/myschema/customize=com.readspring.myannotation.MyNamespaceHandler

spring.schemas

http\://www.shishi.com/myschema/customize.xsd=META-INF/customize.xsd

applicationcontext3.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:customize="http://www.shishi.com/myschema/customize"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.shishi.com/myschema/customize http://www.shishi.com/myschema/customize.xsd">

   <customize:word say="hello world" />

</beans>

目的就是解析到<customize:word say="hello world" /> 並且列印 "helloworld"在控制檯 , 只是為了新增自定義名稱空間到spring, 沒做複雜的行為。

結果:

主要原始碼:

解析自定義名稱空間:

BeanDefinitionParserDelegate是beanfactory的裝飾物件

進最近這張圖的第二個斷點的#resolve:

拿到handlerMappings和對handlerMappings#init (也就是把自定義的parser 全部put 到handler的map中)

進第三個斷點:

get到word對應的那個parser, 在這裡實現具體的業務邏輯