spring的IOC容器能够帮我们自动new对象,对象交给spring管之后我们不用自己手动去new对象了。那么它的原理是什么呢?是怎么实现的呢?下面我来简单的模拟一下spring的机制,相信看完之后就会对spring的原理有一定的了解。
spring使用BeanFactory来实例化、配置和管理对象,但是它只是一个接口,里面有一个getBean()方法。我们一般都不直接用BeanFactory,而是用它的实现类ApplicationContext,这个类会自动解析我们配置的applicationContext.xml,然后根据我们配置的bean来new对象,将new好的对象放进一个Map中,键就是我们bean的id,值就是new的对象。
首先我们建立一个BeanFactory接口
package com.spring; public interface BeanFactory { Object getBean(String id); }
然后建立一个BeanFactory的实现类ClassPathXmlApplicationContext.java
package com.spring; 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.io.SAXReader; public class ClassPathXmlApplicationContext implements BeanFactory { private Map<String, Object> beans = new HashMap<String, Object>(); public ClassPathXmlApplicationContext(String fileName) throws Exception{ SAXReader reader = new SAXReader(); Document document = reader.read(this.getClass().getClassLoader().getResourceAsStream(fileName)); List<Element> elements = document.selectNodes("/beans/bean"); for (Element e : elements) { String id = e.attributeValue("id"); String value = e.attributeValue("class"); Object o = Class.forName(value).newInstance(); beans.put(id, o); } } public Object getBean(String id) { return beans.get(id); } }
然后配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="c" class="com.spring.Car"></bean> <bean id="p" class="com.spring.Plane"></bean> </beans>
创建类的时候顺便演示一下工厂模式,其实BeanFactory它也是一种工厂模式的。
package com.spring; public interface Moveable { void run(); }
package com.spring; public class Car implements Moveable{ public void run(){ System.out.println("拖着四个轮子满街跑car·····"); } }
package com.spring; public class Plane implements Moveable{ public void run() { System.out.println("拖着翅膀天空飞plane......"); } }
现在来看一看效果吧,写一个类测试一下:
package com.spring; import org.dom4j.DocumentException; public class Test { /** * @param args * @throws DocumentException */ public static void main(String[] args) throws Exception { BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); Object o = factory.getBean("c"); Moveable m = (Moveable)o; m.run(); } }
由于Map容器里面保存的是Object类型,所以通过getBean()方法取出来的对象要强制类型转换。
我喜欢,驾驭着代码在风驰电掣中创造完美!我喜欢,操纵着代码在随必所欲中体验生活!我喜欢,书写着代码在时代浪潮中完成经典!每一段新的代码在我手中诞生对我来说就象观看刹那花开的感动!
作者:刘玲
链接:http://www.cnblogs.com/liuling/archive/2013/04/14/BeanFactory.html