Spring中有两个重要概念之一--- IOC (inversion of control) 控制反转,就是对象由beanfactory产生对象,beanfactory里面有一个容器,他加载类对象,容器是一个map。

实现简单模拟beanfactory:

//调用程序

public class Test {public static void main(String[] args) throws Exception{BeanFactory f = new ClassPathXmlApplicationContext("com/d12321/applicationContext.xml");Object o = f.getBean("v");}}

//beanfactory接口

public interface BeanFactory {Object getBean(String id) throws Exception;}

//实现接口的ClassPathXmlApplicationContext对象

public class ClassPathXmlApplicationContext implements BeanFactory {private Map
container = new HashMap
(); //模拟spring的容器public ClassPathXmlApplicationContext(String filename) throws Exception {SAXBuilder sb = new SAXBuilder();Document doc = sb.build(Test.class.getClassLoader().getResourceAsStream(filename));Element root = doc.getRootElement();List list = XPath.selectNodes(root, "/beans/bean");for(int i = 0; i < list.size(); i++) {Element elem = (Element) list.get(i);String it = elem.getAttributeValue("id");String value = elem.getAttributeValue("value");Object o = Class.forName(value).newInstance();container.put(it, o);}}@Overridepublic Object getBean(String id) {return container.get(id);}}

//类对象

public class Car {Car() {System.out.println("car ....");}}

//applicationContext.xml

>

总结:

     1.模拟中用到的重要技术,jdom解析xml文件

     2.Class.forname(类名).newInstance();产生一个类对象

     3.(类名).getClass().getClassLoader().getResourceAsStream("xx/xx/xx.xml"); exp: Document doc = sb.build(Test.class.getClassLoader().getResourceAsStream(filename));