spring的IOC能够帮助我们创建对象,但是具体是如何实现的呢,spring是通过BeanFactory来创建对象,但是他只是一个接口,里面有一个getBean()方法,但我们一般都不用BeanFactory直接用他的实现类ApplicationContext,这个类会帮我们解析applicationcontext.xml,然后根据我们bean的配置来为我们创建对象,讲new好的对象放进一个Map中,key就是id,value就是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 Map<String, Object> beans = new HashMap<String, Object>(); 15 public ClassPathXmlApplicationContext(String fileName) throws Exception{ 16 SAXReader reader = new SAXReader(); 17 Document document = reader.read(this.getClass().getClassLoader().getResourceAsStream(fileName)); 18 List<Element> 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 <?xml version="1.0" encoding="UTF-8"?> 2 <beans> 3 <bean id="c" class="com.spring.Car"></bean> 4 <bean id="p" class="com.spring.Plane"></bean> 5 </beans>
创建类的时候顺便演示一下工厂模式,其实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()方法取出来的对象要强制类型转换。