吃透Spring源码(三):自定义配置文件标签
> Spring的强大之处不仅仅在于它为Java开发者提供了极大便利,更在于它的开放式架构,使得用户可以拥有最大扩展Spring的能力。
我们在用xml定义spring信息时,默认的element只包含beans,bean,import,alias这四个,其它任何标签都属于自定义标签,均需要引入相应的命名空间,如:context,aop标签等。
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
//处理默认的标签元素
parseDefaultElement(ele, delegate);
}
else {
//处理自定义的标签元素
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
对应的源码处理在DefaultBeanDefinitionDocumentReader类的parseBeanDefinitions方法里面。
自定义标签元素
1,定义People.java
public class People {
private String id;
private int age;
private String name;
private String address;
public People(String id, int age, String name, String address) {
this.id = id;
this.age = age;
this.name = name;
this.address = address;
}
public People() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "People{" +
"id='" + id + '\'' +
", age=" + age +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}