标签:
一、概述
1.目标:模拟Spring的Ioc
2.用到的知识点:利用jdom的xpath读取xml文件,反射
二、有如下文件:
1.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="vehicle" class="com.tong.spring.factory.Car"> </bean> </beans>
2.BeanFactory.java
public interface BeanFactory { Object getBean(String id); }
3.ClassPathXmlApplicationContext.java
public class ClassPathXmlApplicationContext implements BeanFactory{ private Map<String, Object> container = new HashMap<String, Object>(); public ClassPathXmlApplicationContext(String fileName) { //读取xml文件 SAXBuilder sb = new SAXBuilder(); Document doc; try { //doc = sb.build(this.getClass().getClassLoader().getResourceAsStream(fileName)); doc = sb.build(fileName); Element root = doc.getRootElement(); List list = XPath.selectNodes(root, "/beans/bean"); for (int i = 0; i < list.size(); i++) { Element element = (Element) list.get(i); String id = element.getAttributeValue("id"); String clazz = element.getAttributeValue("class"); // 利用反射生成例,然后装进容器 Object o = Class.forName(clazz).newInstance(); container.put(id, o); } } catch (Exception e) { e.printStackTrace(); } } @Override public Object getBean(String id) { return container.get(id); } }
4.Movable.java
public interface Movable { void run(); }
5.Car.java
public class Car implements Movable { public void run() { System.out.println("Car running..............."); } }
6.Test.java
public class Test { @org.junit.Test public void test() { BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); Object o = factory.getBean("vehicle"); Movable m = (Movable)o; m.run(); } }
运行结果:
标签:
原文地址:http://www.cnblogs.com/shamgod/p/4587387.html