扩展xsd很简单,官方文档送上:https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/xml-custom.html
照着做没有多大问题,自己也记录一下
第一步:定义bean的结构,自定义xsd就是通过xml生成一个bean而已,这个bean是你提前描述好的,需要怎样生成的,所以当然要提前定义好
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:beans="http://www.springframework.org/schema/beans"
targetNamespace="http://www.mycompany.com/schema/mynsgyc"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
第二步,解析这个xml的beanhandler,既然定义了bean的结构,当然需要知道具体是哪个类来如何生成bean,这个就是需要一个hander 来处理一下,spring提供了解析xml的工具类,所以,你只需要告诉spring,如何把这个xml变成bean就好,具体解析这个恶心的事情,交给spring就好
public class MyNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("gycdate", new SimpleMyBeanDefinitionParser());
}
}
public class SimpleMyBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected Class getBeanClass(Element element) {
return Mybean.class;
}
@Override
protected void doParse(Element element, BeanDefinitionBuilder bean) {
// this will never be null since the schema explicitly requires that a value be supplied
String pattern = element.getAttribute("pattern");
bean.addConstructorArgValue(pattern);
SimpleDateFormat dateFormat=new SimpleDateFormat();
// this however is an optional property
String lenient = element.getAttribute("isgyc");
if (StringUtils.hasText(lenient)) {
bean.addPropertyValue("isgyc", Boolean.valueOf(lenient));
}
}
}
第三步,将xml命令空间和xsd文件,hander三者关联起来,如何关联,resource下面的spring.handers和spring.schemas就好
spring.handers
http://www.mycompany.com/schema/mynsgyc=com.xxx.xxx.MyNamespaceHandler
spring.schemas
http://www.mycompany.com/schema/mynsgyc/spring-mynsgyc.xsd=com/xxx/xxx/TestXsd.xml
最后可以通过注解获取到这个bean
@Autowired
private Mybean mybean;
然后就done了