package com.wxhx.mock; import java.io.InputStream; 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 com.wxhx.bean.BeanDefinition; public class ClassPathXMLApplicationContextMock { private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>(); private Map<String, Object> singletons = new HashMap<String, Object>(); public ClassPathXMLApplicationContextMock(String fileName) { readXML(fileName); } private void instanceBeans() { for (BeanDefinition bean : beanDefines) { try { if (bean.getClassName() != null && !"".equals(bean.getClassName().trim())) { String id = bean.getId(); String className = bean.getClassName(); Object instance = Class.forName(className).newInstance(); singletons.put(id, instance); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void readXML(String fileName) { SAXReader saxReader = new SAXReader(); Document document = null; InputStream stream = null; try { stream = this.getClass().getClassLoader().getResourceAsStream(fileName); Map<String, String> nsMap = new HashMap<String, String>(); nsMap.put("ns", "http://www.springframework.org/schema/beans"); saxReader.getDocumentFactory().setXPathNamespaceURIs(nsMap); document = saxReader.read(stream); XPath path = document.createXPath("//ns:beans/ns:bean"); // path.setNamespaceURIs(nsMap); List<Element> beans = path.selectNodes(document); for (Element element : beans) { String id = element.attributeValue("id"); String className = element.attributeValue("class"); BeanDefinition beanDefinition = new BeanDefinition(); beanDefinition.setId(id); beanDefinition.setClassName(className); beanDefines.add(beanDefinition); } } catch (Exception e) { e.printStackTrace(); } } public Object getBean(String id) { return singletons.get(id); } public static void main(String[] args) { ClassPathXMLApplicationContextMock aa = new ClassPathXMLApplicationContextMock( "applicationContext.xml"); Object obj = aa.getBean("aaa"); System.out.println(obj); } } 请导入dom4j的jar包。