感谢ITCAST发布的免费视频。
模拟bean容器代码:
package junit.test;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
public class MyClassPathXMLApplicationContext {
private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
private Map<String, Object> sigletons = new HashMap<String, Object>();
public MyClassPathXMLApplicationContext(String fileName) {
this.readXML(fileName);
this.instanceBeans();
}
private void instanceBeans() {
// TODO Auto-generated method stub
for (BeanDefinition beanDefinition : beanDefines) {
try {
if (beanDefinition.getClassName() != null && !beanDefinition.getClassName().equals("")) {
sigletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void readXML(String fileName) {
// TODO Auto-generated method stub
SAXReader saxReader = new SAXReader();
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader().getResource(fileName);
Map<String, String> nsMap = new HashMap<String, String>();
XPath xsub = null;
List<Element> beans = null;
document = saxReader.read(xmlpath);
nsMap.put("ns", "http://www.springframework.org/schema/beans"); //add namespace
xsub = document.createXPath("//ns:beans/ns:bean"); //create beans/bean query path
xsub.setNamespaceURIs(nsMap); //set namespace
beans = xsub.selectNodes(document); //get nodes of the document
for (Element element : beans) {
String id = element.attributeValue("id");
String clazz = element.attributeValue("class");
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
beanDefines.add(beanDefine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Object getBean(String beanName) {
return this.sigletons.get(beanName);
}
}
package junit.test;
public class BeanDefinition {
private String id;
private String className;
public BeanDefinition(String id, String className) {
this.id = id;
this.className = className;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
这里只是阐释原理,实际Spring的实现比这个要复杂很多。