Spring的XML标签按照解析方式划分,可以分为两类:默认命名空间标签和自定义标签。默认命名空间一共有四个:beans bean import alias,其他的标签全部叫做自定义标签
一个标签的解析加载一共需要经过如下几个流程:
Spring解析自定义标签需要的信息有:BeanDefinitionParser、NamespaceHandler、spring.schemas、spring.handlers、xsd文件、xml文件、加载启动类ClassPathXmlApplicationContext
Spring解析自定义标签的实际流程封装的比较深,需要从refresh()中的obtainFreshBeanFactory()方法作为入口,慢慢深入探索。只要细心的捋一遍内部实现就能搞明白,实打实的纸老虎,不难的。
定义BeanDefinitionParser
public class DeerBeanDefinitionParser implements BeanDefinitionParser {
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
String address = element.getAttribute("address");
String country = element.getAttribute("country");
String color = element.getAttribute("color");
System.out.println("address is :" + address);
System.out.println("country is :" + country);
System.out.println("color is :" + color);
return null;
}
}
定义NamespaceHandler
public class DeerNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("deer", new DeerBeanDefinitionParser());
}
}
创建spring.schemas,spring.schemas文件需要放置在resources/META-INF下才能被Spring扫描到
http\://www.deerhang.org/schema/deer.xsd=xml/deer.xsd
创建spring.handlers,放置位置同spring.shemas
http\://www.deerhang.org/schema/deer=com.xxx.mine.DeerNamespaceHandler
创建xsd文件,xsd文件必须放在resource下,路径对应spring.schames中的xsd位置
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns="http://www.deerhang.org/schema/deer"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.deerhang.org/schema/deer">
<xsd:element name="deer">
<xsd:complexType>
<xsd:attribute name="country" type="xsd:string"></xsd:attribute>
<xsd:attribute name="color" type="xsd:string"></xsd:attribute>
<xsd:attribute name="address" type="xsd:string"></xsd:attribute>
</xsd:complexType>
</xsd:element>
</xsd:schema>
创建xml文件,用来定义配置信息,xml文件同样放置在resource下applicationContext.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:hang="http://www.deerhang.org/schema/deer"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.deerhang.org/schema/deer http://www.deerhang.org/schema/deer.xsd">
<hang:deer address="清原" color="黄色" country="中国"></hang:deer>
</beans>
最后一步配置启动类ClassPathXmlApplicationContext
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
原文:https://www.cnblogs.com/deer-hang/p/14900543.html