- 核心技术点:XML解析 + 反射
- 具体思路: 配置XML文件,程序读配置文件,把信息读出来,创建对象,装到Map里,再从Map里把对象取出来。
1、根据需求编写 XML 文件,配置需要创建的 bean。
2、编写程序读取 XML 文件(dom4j 解析 XML),获取 bean 相关信息,id、类、属性。
3、根据第 2 步获取到的信息,结合反射机制动态创建对象,同时完成属性的赋值。
4、将创建好的 bean 存入 Map 集合,设置 key - value 映射,key 就是 bean 中 id 值,value 就是 bean 对象。
5、提供方法从 Map 中通过 id 获取到对应的 value。
ApplicationContext 接口
package ioc;
public interface ApplicationContext {
public Object getBean(String id);
}
ClassPathXmlApplicationContext 类
package ioc;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ClassPathXmlApplicationContext implements ApplicationContext{
private Map<String, Object> ioc = new HashMap<String, Object>();
public ClassPathXmlApplicationContext(String path) {
try {
//1. 将spring.xml转成Document对象
SAXReader reader = new SAXReader();
Document document = reader.read("./src/main/resources/" + path);
//2. dog4j 解析 XML
//2.1 首先获取根节点对象<beans>
Element root = document.getRootElement();
//2.2 迭代获取子节点对象<bean>
//获取一个迭代器
Iterator<Element> iterator = root.elementIterator();
//循环
while(iterator.hasNext()){//若迭代器中有下一个
Element element = iterator.next();
//2.2.1 获取key,即bean中的id属性值
String id = element.attributeValue("id");//把属性名id传进去
//2.2.2 获取全类名,即bean中的class属性值
String className = element.attributeValue("class");//把属性名class传进去
//2.2.3 获去value,即通过全类名,通过反射机制调用无参构造函数创建对象
//2.2.3.1 通过反射机制获取class对象
Class clazz = Class.forName(className);
/*
//2.2.3.2 获取无参构造方法对象
Constructor constructor = clazz.getConstructor();
//2.2.3.3 创建目标对象
Object object = constructor.newInstance();
*/
//2.2.3.2 调用无参构造函数创建目标对象
//如果使用无参数构造方法创建对象,可简化为:Class对象的newInstance方法,即Class对象.newInstance()(常用此操作)
Object object = clazz.newInstance();
//2.2.4 给目标对象赋值
Iterator<Element> beanIter = element.elementIterator();
while(beanIter.hasNext()){
Element property = beanIter.next();
//获取property中name、value、ref的值
String name = property.attributeValue("name");
String valueStr = property.attributeValue("value");
String ref = property.attributeValue("ref");
//通过反射调用目标对象的set方法完成对对象的赋值
//字符串拼接得到set方法名
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
//获取成员变量对象
Field field = clazz.getDeclaredField(name);// 获取private修饰的成员变量
//第一个参数是set方法名,第二个参数是set方法的参数类型
Method method = clazz.getDeclaredMethod(methodName, field.getType());
if(ref == null){//<property name="" value=""/>
//根据成员变量的数据类型将 valueStr 进行转换
Object value = null;
if(field.getType().getName() == "long"){
value = Long.parseLong(valueStr);//包装类方法将String类型转成long类型
}
if(field.getType().getName() == "java.lang.String"){
value = valueStr;
}
if(field.getType().getName() == "int"){
value = Integer.parseInt(valueStr);
}
//执行set方法
method.invoke(object, value);
}else{//<property name="" ref=""/> 依赖注入DI
Object refValue = ioc.get(ref);
//执行set方法
method.invoke(object, refValue);
}
}
//2.2.5 key和value存入map集合
ioc.put(id, object);
}
//System.out.println(ioc);
} catch (DocumentException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public Object getBean(String id) {
return ioc.get(id);
}
}
调用 getBean() 方法通过 id 获取到 Map 中对应的 value,也就是对象
package ioc;
import entity.Student;
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Student student = (Student) applicationContext.getBean("student");
System.out.println(student);
}
}