Spring扩展自定义的XML标签
在网上搜了许多,感觉不够全面,就找了官方文档,下面记录如何找到对应的文档进入
网上许多博客都是以dateformat为实例进行编写的,通过官方的foo,能够学到更多的东西,下面贴一段代码,在官方示例上改了一点解析代码:
package com.theory.springdemo; import java.util.List; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; public class ComponentBeanDefinitionParser extends AbstractBeanDefinitionParser { protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { return parseComponentElement2(element); } // 这个是自己编写的,没有采用官方文档中定义的示例ComponentFactoryBean private static AbstractBeanDefinition parseComponentElement2(Element ele) { BeanDefinitionBuilder bean = BeanDefinitionBuilder.rootBeanDefinition(Component.class); bean.addPropertyValue("name", ele.getAttribute("name")); List<Element> childElements = DomUtils.getChildElementsByTagName(ele, "component"); //List<BeanDefinition> children = new ArrayList<>(); // 不能用这个,转换之类的会报错,ManageList是继承的ArrayList ManagedList<BeanDefinition> children = new ManagedList<BeanDefinition>(childElements.size()); for (Element child : childElements) { AbstractBeanDefinition cc = parseComponentElement2(child); children.add(cc); } bean.addPropertyValue("components", children); return bean.getBeanDefinition(); } // 以下的代码都是官方文档中的 private static AbstractBeanDefinition parseComponentElement(Element element) { BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(ComponentFactoryBean.class); factory.addPropertyValue("parent", parseComponent(element)); List<Element> childElements = DomUtils.getChildElementsByTagName(element, "component"); if (childElements != null && childElements.size() > 0) { parseChildComponents(childElements, factory); } return factory.getBeanDefinition(); } private static BeanDefinition parseComponent(Element element) { BeanDefinitionBuilder component = BeanDefinitionBuilder.rootBeanDefinition(Component.class); component.addPropertyValue("name", element.getAttribute("name")); return component.getBeanDefinition(); } private static void parseChildComponents(List<Element> childElements, BeanDefinitionBuilder factory) { ManagedList<BeanDefinition> children = new ManagedList<BeanDefinition>(childElements.size()); for (Element element : childElements) { children.add(parseComponentElement(element)); } factory.addPropertyValue("children", children); } }