Java-马士兵设计模式学习笔记-工厂模式-用Jdom模拟Spring
一、概述
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(fileName);
//Test.java要改为BeanFactory factory = new ClassPathXmlApplicationContext("com/tong/spring/factory/applicationContext.xml");
//否则付出现“java.net.MalformedURLException”
doc = sb.build(this.getClass().getClassLoader().getResourceAsStream(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");
BeanFactory factory = new ClassPathXmlApplicationContext("com/tong/spring/factory/applicationContext.xml");
Object o = factory.getBean("vehicle");
Movable m = (Movable)o;
m.run();
}
}
运行结果:

You can do anything you set your mind to, man!

浙公网安备 33010602011771号