码迷,mamicode.com
首页 > 编程语言 > 详细

Java 模拟Spring

时间:2015-06-19 01:20:36      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

 一、概述

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();
	}
}

  

运行结果:

技术分享

 

Java 模拟Spring

标签:

原文地址:http://www.cnblogs.com/shamgod/p/4587387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!