自定义spring标签解析器
bean在spring中,首先是先将配置文件中的bean信息解析成BeanDefinition即bean定义信息对象。
对于bean的申明有多中方式,拿典型的xml申明来说,其大致的流程:
加载xml文件 :AbstractBeanDefinitionReader#loadBeanDefinitions(String, Set< Resource> actualResources)
根据xml schema文件解析校验xml配置成document:XmlBeanDefinitionReader#doLoadDocument
根据xml的namespace获取到对应的解析器NamespaceHandler:BeanDefinitionParserDelegate#parseCustomElement(Element, BeanDefinition)
将xml中的属性赋给BeanDefinition:实现类AbstractSingleBeanDefinitionParser
public class MyTag {
private String tagName;
public void setTagName(String tagName) {
this.tagName = tagName;
}
public String getTagName() {
return tagName;
}
}
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
public class TagNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("self", new TagSingleBeanDefinitionParser());
}
}
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.w3c.dom.Element;
public class TagSingleBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected Class<?> getBeanClass(Element element) {
return MyTag.class;
}
@Override
protected void doParse(Element element, BeanDefinitionBuilder builder) {
String tagName = element.getAttribute("tagName");
builder.addPropertyValue("tagName", tagName);
}
}
spring.handlers
http\://www.xiahaila.com/schema/tag=com.xiahaila.study.spring.tag.TagNamespaceHandler
spring.schemas
http\://www.xiahaila.com/schema/tag.xsd=META-INF/tag.xsd
tag.xsd
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.xiahaila.com/schema/tag"
xmlns:tns="http://www.xiahaila.com/schema/tag"
elementFormDefault="qualified">
<element name="self">
<complexType>
<attribute name ="id" type = "string"/>
<attribute name="tagName" type="string"/>
</complexType>
</element>
</schema>
xml文件bean信息配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tag="http://www.xiahaila.com/schema/tag"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.xiahaila.com/schema/tag
http://www.xiahaila.com/schema/tag.xsd">
<tag:self id="selfTag" tagName="xxxxxnnnnnns" ></tag:self>
</beans>
spring.schemas 放xml和schema的映射
spring.handlers 放xml属性和class属性的赋值和创建beanDefine