spring schema 扩展

阅读更多

spring 可以基于schema 扩展,自定义 schema。参考文档自己搭了个应用试验了一下:

 


spring schema 扩展_第1张图片

首先看下自己写的 myns.xsd

 

 



	

	
		
			
				
					
					
				
			
		
	

 

然后看下我的applicationContxt.xml配置:

 



	

很明显实现了个自定义的bean ,这个bean有两个属性,一个是时间的格式,另外一个不知道啥东西。

 

然后在META-INF下面写了两个文件,

spring.handlers:用来描述如何处理自定义的namespace

 

http\://www.yjhexy.com/schema/myns=com.yajun.balance.spring.MyNamespaceHandler

 spring.schemas:描述schema的位置

 

http\://www.yjhexy.com/schema/myns/myns.xsd=com/yajun/balance/spring/myns.xsd

 

然后是需要两个类,一个处理namespace,一个处理beanDefinition

 

 

package com.yajun.balance.spring;

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class MyNamespaceHandler extends NamespaceHandlerSupport {

    public void init() {
        registerBeanDefinitionParser("dateformat", new SimpleDateFormatBeanDefinitionParser());
    }

}
 

 

 

package com.yajun.balance.spring;

import java.text.SimpleDateFormat;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

public class SimpleDateFormatBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

    protected Class getBeanClass(Element element) {
        return SimpleDateFormat.class;
    }

    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);

        // this however is an optional property
        String lenient = element.getAttribute("lenient");
        if (StringUtils.hasText(lenient)) {
            bean.addPropertyValue("lenient", Boolean.valueOf(lenient));
        }
    }
}

 

最后main输出试试:

 

package com.yajun.balance.spring;

import java.text.SimpleDateFormat;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        SimpleDateFormat f = (SimpleDateFormat) ctx.getBean("dateFormat");
        System.out.println(f);
    }
}

 

===========================

 

xsd 基础 常用的简单 类型

 

  • xs:string
  • xs:decimal
  • xs:integer
  • xs:boolean
  • xs:date
  • xs:time
  • xs:positiveInteger
  • spring schema 扩展_第2张图片
  • 大小: 17 KB
  • 查看图片附件

你可能感兴趣的:(Spring,Bean,XML,F#)