spring管理bean容器(笔记)[继](一)

2014-11-23 23:34:41 · 作者: · 浏览: 2
当了解了spring容器的实例化之后,我们可以进行简单的进行模拟这个过程:
1.首先进行加载spring的xml配置文件
2.进行解析这个配置文件,将节点映射成一个类
3.进行对
4.然后在这个集合中根据id进行bean。
复制代码
mybens.xml配置文件
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
复制代码
节点对应的类,这里只简单的存储id和class类型,采用的是xml配置使用bean的类构造器进行实例化
复制代码
package cn.can.myspring;
//xml中节点的
//对应的类
public class MyBean {
private String id;
private String className;
public MyBean() {
super();
}
public MyBean(String id, String className) {
super();
this.id = id;
this.className = className;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
复制代码
关键是下面的解析xml和实例化,用了xpath进行解析xml和反射机制进行实例化类。
复制代码
package cn.can.myspring;
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;
import cn.can.myspring.exception.NoIdClassException;
public class MyApplicationContext {
// 因为bean是多个的
private List myBeans = new ArrayList();
  //存储实例化之后的引用
private Map singles = new HashMap();
// 这里可以传入一个xml,或者传入多个xml
public MyApplicationContext() {
}
public Object getBean(String id) throws NoIdClassException{
if(singles.size() <= 0){
throw new NoIdClassException("不存在这个类");
}
Object obj = singles.get(id);
if(obj == null){
throw new NoIdClassException("不存在这个类");
}
return obj;
}
public MyApplicationContext(String fileName) {
init(fileName);// 获得xml的信息之后
initObject();// 进行实例化
}
// 2.进行实例化
private void initObject() {
try {
if (myBeans != null && myBeans.size() > 0) {
// 遍历bean //
for (MyBean bean : myBeans) {
String id = bean.getId();
String clazz = bean.getClassName();
if (id != null && !"".equals(id)) {
if (clazz != null && !"".equals(clazz)) {
// 这个时候进行实例化
Class cl = Class.forName(clazz);
Object o = cl.newInstance();
singles.put(id, o);
}
}
}
}
} catch (Exception e) {
}
}
public MyApplicationContext(String[] fileNames) {
}
// 1.进行加载xml,解析xml文件
private void init(String fileName) {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader()
.getResource(fileName);
document = saxReader.read(xmlpath);
Map nsMap = new HashMap();
nsMap.put("ns", "http://www.springframework.org/schem