Spring的beanFacotry模擬

Spring中有兩個重要概念之一--- IOC (inversion of control) 控制反轉,就是對象由beanfactory產生對象,beanfactory裏面有一個容器,他加載類對象,容器是一個map。java

實現簡單模擬beanfactory:spring

//調用程序app

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接口dom

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

//實現接口的ClassPathXmlApplicationContext對象ide

public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String,Object>  container = new HashMap<String, Object>(); //模擬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);
}
}
@Override
public Object getBean(String id) {
return container.get(id);
}
}

//類對象ui

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

//applicationContext.xmlxml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="v" value="com.d12321.Car">
</bean>>
</beans

總結:對象

     1.模擬中用到的重要技術,jdom解析xml文件接口

     2.Class.forname(類名).newInstance();產生一個類對象get

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

相關文章
相關標籤/搜索