package 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;
public class ClassPathXMLApplicationContext {
private List<BeanDefintion> beanDefines=new ArrayList<BeanDefintion>();
private Map<String,Object> sigletons=new HashMap<String, Object>();
public ClassPathXMLApplicationContext(String filename){
this.readXML(filename);
this.instanceBeans();
}
//完成bean实例化
private void instanceBeans() {
for(BeanDefintion beanDefintion:beanDefines){
try {
if(beanDefintion.getClazz()!=null && !"".equals(beanDefintion.getClazz().trim()))
sigletons.put(beanDefintion.getId(), Class.forName(beanDefintion.getClazz()).newInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//读取XML
private void readXML(String filename) {
// TODO Auto-generated method stub
SAXReader saxReader=new SAXReader();
Document document=null;
try {
URL xmlpath=this.getClass().getClassLoader().getResource(filename);
document=saxReader.read(xmlpath);
Map<String, String> nsMap=new HashMap<String, String>();
nsMap.put("ns", "加入命名空间
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");
String clazz=element.attributeValue("class");
BeanDefintion beanDefine=new BeanDefintion(id,clazz);
beanDefines.add(beanDefine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//获取bean实例
public Object getBean(String beanName){
return this.sigletons.get(beanName);
}
}