扩展spring schema 的方法, 代码下载
By:Roy.LiuLast updated:2013-12-10
在写程序框架的过程中,经常为了简化程序,可能需要自定义schema, SPRING 对于JAVA开发者来说,是很好的工具,因此基于SPRING schema 的扩展对框架有很大用处。
比如做成自己的schema 之后,就可以在 xml 配置文件中类似如下的定义:
package com.springwork.xml;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
public class MyNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("people", new PeopleBeanDefinitionParser());
}
}package com.springwork.xml;
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 PeopleBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
protected Class getBeanClass(Element element) {
return People.class;
}
protected void doParse(Element element, BeanDefinitionBuilder bean) {
String name = element.getAttribute("name");
String age = element.getAttribute("age");
String id = element.getAttribute("id");
if (StringUtils.hasText(id)) {
bean.addPropertyValue("id", id);
}
if (StringUtils.hasText(name)) {
bean.addPropertyValue("name", name);
}
if (StringUtils.hasText(age)) {
bean.addPropertyValue("age", Integer.valueOf(age));
}
}
}package com.springwork.xml;
public class People {
private String name;
private int age;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}测试代码: 你就可以看到结果了。
package com.springwork.xml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/config/application.xml");
People p = (People)ctx.getBean("cutesource");
System.out.println(p.getId());
System.out.println(p.getName());
System.out.println(p.getAge());
}
}附上原代码,打包,去掉了SPRING JAR 包,大家自己加进去。太大了。测试工程里面,还加入了一个servlet的测试。
点击下载spring schema 扩展源代码
PS: 忘记另一个重点了,在springcomponent工程里面,要注意META-INF 文件夹中的 spring.handlers, spring.schemas.配置。
From:一号门

COMMENTS