3.编码剖析Spring管理Bean的原理
一.使用dom4j读取spring 配置文件
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.DocumentException;import org.dom4j.Element;import org.dom4j.XPath;import org.dom4j.io.SAXReader;public class ZhkClassPathXMLApplicationContext{ private List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>(); private Map<String,Object> singletones = new HashMap<String,Object>(); public ZhkClassPathXMLApplicationContext(String filename) { this.readXML(filename); this.instanceBeans(); } //完成bean实例化 private void instanceBeans() { for(BeanDefinition beanDefine : beanDefinitions) { try { if (null != beanDefine.getClassName() && !"".equals(beanDefine.getClassName().trim())) { singletones.put(beanDefine.getId(), Class.forName(beanDefine.getClassName()) .newInstance()); } } catch (Exception e) { e.printStackTrace(); } } } /** <读取配置文件> * @param filename [参数说明] */ private void readXML(String filename) { 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", "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 className = element.attributeValue("class"); //获取class属性值 BeanDefinition beanDefine = new BeanDefinition(id,className); beanDefinitions.add(beanDefine); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** <获取bean实例> * @param beanName */ public Object getBean(String beanName) { return this.singletones.get(beanName); }}package junit.test;public class BeanDefinition{ private String id; private String className; public BeanDefinition(String id, String className) { this.id = id; this.className = className; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } }package junit.test;import org.junit.BeforeClass;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.spring.service.PersonService;public class SpringTest{ @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void instanceSpring() { ZhkClassPathXMLApplicationContext ctx = new ZhkClassPathXMLApplicationContext("beans.xml"); PersonService personservice = (PersonService)ctx.getBean("personService"); personservice.save(); }}