作者:郭原雪2865 | 来源:互联网 | 2023-05-17 11:44
参考:http:blog.csdn.netxiangsuixinshengarticledetails6539324增加点:1.bean的书写顺序随意,不要求r
参考:http://blog.csdn.net/xiangsuixinsheng/article/details/6539324
增加点:
1.bean的书写顺序随意,不要求ref的bean一定已经注册;
2.使用dom4j实现
一、JAVA实现脚本
package com.bjsxt.spring.utils;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.bjsxt.spring.demo.Demo1;
import com.bjsxt.spring.demo.Demo2;
public class ClassPathXmlApplicationContext {
private Map beans = new HashMap(); //bean容器
private List elements; //解析xml生成的中间数据
public ClassPathXmlApplicationContext(String resource) throws Exception{
//初始化容器
init(resource);
}
/**
* 加载XML文件
* @param resource
* @throws Exception
*/
@SuppressWarnings({ "unchecked", "unused" })
private void init(String resource)throws Exception{
SAXReader reader = new SAXReader();
InputStream in = this.getClass().getResourceAsStream(resource);
elements = reader.read(in).getRootElement().elements("bean");
for (Element e : elements) {
parseElement(e);
}
}
/**
* 解析XML节点生成出Bean放到容器中
* @param element
* @throws Exception
*/
private void parseElement(Element element)throws Exception{
// 获取对应id,class,propertity
String id = element.attributeValue("id");
String clazz = element.attributeValue("class");
Object o = Class.forName(clazz).newInstance();
beans.put(id, o); //将类注入容器
@SuppressWarnings("unchecked")
List child = element.elements();
for (Element e : child) {
String name = e.attributeValue("name");
String value = e.attributeValue("value");
String ref = e.attributeValue("ref");
Object beanObject = null;
if(null!=ref && !("".equals(ref))){
// 判断beans中是否存在
beanObject = beans.get(ref);
if(null == beanObject){//若在容器中不存在,暂时不处理
for (Element e1 : elements) {
String id1 = e1.attributeValue("id");
if(id1.equals(ref)){
parseElement(e1); //递归调用注册类到容器
break;
}
}
}
beanObject = beans.get(ref);
}
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); //拼装生成setter方法
if(null==value || "".equals(value)){
//若为结构
Method m = o.getClass().getMethod(methodName, beanObject.getClass());
m.invoke(o, beanObject);
}else{
//若为结构
Method m = o.getClass().getMethod(methodName, value.getClass());
m.invoke(o, value);
}
}
}
/**
* 获取Bean
* @param id
* @return
*/
public Object getBean(String id){
return beans.get(id);
}
public static void main(String[] args) throws Exception{
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Demo1 d1 = (Demo1)ctx.getBean("demo01");
Demo2 d2 = (Demo2)ctx.getBean("demo02");
System.out.println(d1);
System.out.println(d2);
}
二、XML配置脚本例子: