简单模拟Spring管理Bean对象

1: 首先我们要利用dom4j进行xml的解析,将所有的bean的配置读取出来。

2:利用java的反射机制进行对象的实例化。

3: 直接获得对象

 

package cn.Junit.test;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.config.BeanDefinition;

public class MyClassPathXmlApplicationContext {
	private String filemame;
	private List<DefBean> list = new ArrayList<DefBean>();
	private Map<String, Object> singletons = new HashMap<String, Object>();

	public MyClassPathXmlApplicationContext() {
		super();
		// TODO Auto-generated constructor stub
	}

	public MyClassPathXmlApplicationContext(String filemame) {
		//1. 读取XML配置文件
		this.readXML(filemame);
		//2.实例化对象
		this.instanceBean();
	}

	private void instanceBean() {
		for (DefBean bean : list) {
			try {
				singletons.put(bean.getId(), Class.forName(bean.getClassName()).newInstance());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void readXML(String filemame) {
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			URL xmlpath = this.getClass().getClassLoader()
					.getResource(filemame);
			document = saxReader.read(xmlpath);
			
			Map<String, String> nsMap = new HashMap<String, String>();
			nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名空间
			XPath xsub = document.createXPath("//ns:beans/ns:bean");// 创建beans/bean查询路径
			xsub.setNamespaceURIs(nsMap);// 设置命名空间
			List<Element> beans = xsub.selectNodes(document);// 获取文档下所有bean节点
			for (Element element : beans) {
				String id = element.attributeValue("id");// 获取id属性值
				String clazz = element.attributeValue("class"); // 获取class属性值
				DefBean bean = new DefBean(id, clazz);
				list.add(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//3. 获得bean对象
	public Object getBean(String key) {
		return singletons.get(key);
	}

}

  

 

posted @ 2014-02-20 09:34  E_star  阅读(575)  评论(0编辑  收藏  举报