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, 在这里实现具体的业务逻辑
完