In -depth analysis of the code delegate.parseCustomElement(ele);
For dubbo , it uses the functional features of spring custom tag parsing. The process of Spring custom tag parsing is as follows:
- Create a component that needs to be extended
- Define an XSD description file content
- Create a class that implements the BeanDefinitionParser interface to parse definitions in XSD files and definitions in components
- Create a Handler component that extends NamespaceHandlerSupport to register the component with the Spring container
- Writing Spring.handlers and Spring.schemas files
Now start using custom tag parsing by following the steps above
1. Create a class to receive the properties in the configuration file
public class People { private String id; private String name; private Integer age; // 省略get/set方法
- Create an xsd file describing the xml syntax constraints
-
<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns="http://blog.csdn.net/cutesource/schema/people" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:beans="http://www.springframework.org/schema/beans" targetNamespace="http://blog.csdn.net/cutesource/schema/people" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xsd:import namespace="http://www.springframework.org/schema/beans" /> <xsd:element name="people"> <xsd:complexType> <xsd:complexContent> <xsd:extension base="beans:identifiedType"> <xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="age" type="xsd:int" /> </xsd:extension> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:schema> The age and name attributes are defined in xsd, which correspond to the attributes in the people entity one by one
- Create a file that implements the BeanDefinitionParser interface to parse definitions in XSD and XML files
-
package com.spring.test.parser; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.util.StringUtils; import org.w3c.dom.Element; import com.spring.test.pojo.People; public class PeopleBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { // Element对应的类 @Override protected Class getBeanClass(Element element) { return People.class; } // Parse and extract the corresponding element from element @Override protected void doParse(Element element, BeanDefinitionBuilder bean) { String name = element.getAttribute("name"); String age = element.getAttribute("age"); String id = element.getAttribute("id" ); if (StringUtils.hasText(id)) { // Put the extracted data into BeanDefinitionBuilder, after parsing is completed, put it into unified registration to beanFactory bean.addPropertyValue("id" , id); } if (StringUtils.hasText(name)) { bean.addPropertyValue("name", name); } if (StringUtils.hasText(age)) { bean.addPropertyValue("age", Integer.valueOf(age)); } } }