本文共 2577 字,大约阅读时间需要 8 分钟。
spring的IOC容器能够帮我们自动new对象,对象交给spring管之后我们不用自己手动去new对象了。那么它的原理是什么呢?是怎么实现的呢?下面我来简单的模拟一下spring的机制,相信看完之后就会对spring的原理有一定的了解。
spring使用BeanFactory来实例化、配置和管理对象,但是它只是一个接口,里面有一个getBean()方法。我们一般都不直接用BeanFactory,而是用它的实现类ApplicationContext,这个类会自动解析我们配置的applicationContext.xml,然后根据我们配置的bean来new对象,将new好的对象放进一个Map中,键就是我们bean的id,值就是new的对象。
首先我们建立一个BeanFactory接口
1 package com.spring;2 3 public interface BeanFactory {4 Object getBean(String id);5 }
然后建立一个BeanFactory的实现类ClassPathXmlApplicationContext.java
1 package com.spring; 2 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import org.dom4j.Document; 8 import org.dom4j.DocumentException; 9 import org.dom4j.Element;10 import org.dom4j.io.SAXReader;11 12 13 public class ClassPathXmlApplicationContext implements BeanFactory {14 private Mapbeans = new HashMap ();15 public ClassPathXmlApplicationContext(String fileName) throws Exception{16 SAXReader reader = new SAXReader();17 Document document = reader.read(this.getClass().getClassLoader().getResourceAsStream(fileName));18 List elements = document.selectNodes("/beans/bean");19 for (Element e : elements) {20 String id = e.attributeValue("id");21 String value = e.attributeValue("class");22 Object o = Class.forName(value).newInstance();23 beans.put(id, o);24 }25 }26 27 public Object getBean(String id) {28 return beans.get(id);29 }30 31 }
然后配置applicationContext.xml
1 23 4 5
创建类的时候顺便演示一下工厂模式,其实BeanFactory它也是一种工厂模式的。
1 package com.spring;2 3 public interface Moveable {4 void run();5 }
1 package com.spring;2 3 public class Car implements Moveable{4 5 public void run(){6 System.out.println("拖着四个轮子满街跑car·····");7 }8 }
1 package com.spring;2 3 public class Plane implements Moveable{4 5 public void run() {6 System.out.println("拖着翅膀天空飞plane......");7 }8 9 }
现在来看一看效果吧,写一个类测试一下:
1 package com.spring; 2 3 import org.dom4j.DocumentException; 4 5 public class Test { 6 7 /** 8 * @param args 9 * @throws DocumentException 10 */11 public static void main(String[] args) throws Exception {12 BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");13 Object o = factory.getBean("c");14 Moveable m = (Moveable)o;15 m.run();16 }17 18 }
由于Map容器里面保存的是Object类型,所以通过getBean()方法取出来的对象要强制类型转换。
转载地址:http://gxall.baihongyu.com/