Spring原理自我实践之IOC的模拟实现
2009-09-18 00:00:00 来源:WEB开发网在学习Spring的过程中,为了更加透彻的理解IOC容器,在讲师的分析下,自我实践了一下IOC的模拟实现:
Class_1:核心的模拟IOC类,其中注释已经十分清晰
Java代码
package com.java.mySpring;
import java.util.HashMap;
import java.util.Map;
import com.java.util.AnalyzeXMLUtil;
import com.java.util.ReflectHelper;
/**
* 实例说明:模拟IOC的原理
*
* @author citizen
*
*/
public class MyIOC {
// 配置文件的绝对路径
private static final String XML_PATH = "F:/eclipse-jee-ganymede-SR2-win32(1)/project/MyIOC/src/beans.xml";
private Map<String, Object> beansMap = new HashMap<String, Object>();// 模拟存储对象的Map容器
/**
* 创建IOC容器
*
* @throws Exception
*/
private void creatIOC() throws Exception {
// 取得配置文件中所有的bean,将id为key创建在Map中
String[] ids = AnalyzeXMLUtil.getAttributeValue(XML_PATH,
"/beans/bean", "id");
for (int i = 0; i < ids.length; i++) {
createBean(ids[i]);
}
}
/**
* 在容器初始化时,载入对象
*
* @throws Exception
*/
@SuppressWarnings("static-access")
public MyIOC() throws Exception {
creatIOC();
}
/**
* 创建Bean在容器里
*
* @param beanId
* Bean的Id
* @return
* @throws Exception
*/
private Object createBean(String beanId) throws Exception {
// TODO Auto-generated method stub
String className = AnalyzeXMLUtil.getSingleAttributeValue(XML_PATH,"/beans/bean[@id='" + beanId + "']", "class");
Object[] args = new Object[0];
Object bean = null;
// 如果已存在该对象,直接返回该对象
if (beansMap.containsKey(beanId)) {
return beansMap.get(beanId);
} else {// 如果不存在,创建对象
bean = ReflectHelper.newInstance(className, args);
}
//取得某一个Bean所有的属性名
String[] propNames = AnalyzeXMLUtil.getAttributeValue(XML_PATH,"/beans/bean[@id='" + beanId + "']/property", "name");
for (int j = 0; j < propNames.length; j++) {
//取得某一个Bean对应的所有属性的值
String propValue = AnalyzeXMLUtil.getSingleAttributeValue(XML_PATH,
"/beans/bean[@id='" + beanId + "']/property[@name='"
+ propNames[j] + "']", "value");
// 如果Bean的属性是基本类型,注入该属性值
if (propValue != null && propValue.length() > 0) {
/*
* Object[] setArgs = new Object[1]; setArgs[0] = propValue;
* ReflectHelper.invokeMethod(bean,
* ReflectHelper.getSetMethodNameByFieldName(propNames[j]),
* setArgs);
*/
ReflectHelper.setFieldValue(bean, propNames[j], propValue);
}
// 如果Bean的属性是引用Bean,可能要递归创建依赖的Bean
else {
propValue = AnalyzeXMLUtil.getSingleAttributeValue(XML_PATH,"/beans/bean[@id='" + beanId + "']/property[@name='"
+ propNames[j] + "']", "ref");
Object dependBean = createBean(propValue);//递归调用
ReflectHelper.setFieldValue(bean, propNames[j], dependBean);
}
}
if (!beansMap.containsKey(beanId)) {
beansMap.put(beanId, bean);
}
return beansMap.get(beanId);
}
/**
* 按ID取得bean
*
* @param beanId
* @return
*/
public Object getBean(String beanId) {
System.out.println("要取得的:" + beanId);
return this.beansMap.get(beanId);
}
}
更多精彩
赞助商链接