SpringIOC
SpringIOC就是将创建对象的控制权交给Spring容器来进行管理。容器就是XML文件
实现思路:
1、使用dom4j来读取XML文件,获取document对象
2、通过id来获取到配置文件中class里面的值,使用反射技术进行实例化
3、property属性里面的name和value,我们可以使用反射给这些属性进行赋值
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="user" class="cn.zyyx.json.User">
<property name="id" value="8"/>
<property name="name" value="紫炎易霄"/>
<property name="age" value="29"/>
</bean>
</beans>
代码实现类
package cn.zyyx.json;
import java.lang.reflect.Field;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ApplicationContext {
private String path;
public ApplicationContext(String path) {
this.path = path;
}
/**
* 通过id来获得对象
*/
public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException{
Object obj = null;
//使用Dom4j加载配置文件
SAXReader saxReader = new SAXReader();
//获得XML文件树
Document document = saxReader.read(this.getClass().getClassLoader().getResourceAsStream(path));
//获得根节点
Element rootElement = document.getRootElement();
//通过根节点来获得儿子节点
List<Element> sons = rootElement.elements();
for (Element son : sons) {
//获得儿子节点里面的id
String id = son.attributeValue("id");
if(!beanId.equals(id)){
continue;
}
//获得儿子节点的类路径
String classPath = son.attributeValue("class");
//使用反射获得类对象
Class<User> clazz = (Class<User>) Class.forName(classPath);
obj = clazz.newInstance();
//使用儿子节点来获得孙子节点
List<Element> grandSons = son.elements();
for (Element grandSon : grandSons) {
//获得孙子节点里面的属性
String name = grandSon.attributeValue("name");
String value = grandSon.attributeValue("value");
Field field = clazz.getDeclaredField(name);
//设置权限
field.setAccessible(true);
if(field.getType().toString().contains("String")){
field.set(obj, value);
}
if(field.getType().toString().contains("Integer")){
field.set(obj,Integer.valueOf(value));
}
}
}
return obj;
}
}
测试类
public static void main(String[] args) throws Exception {
//负责加载Spring的核心配置文件
ApplicationContext ac = new ApplicationContext("applicationContext.xml");
User user = (User) ac.getBean("user");
System.out.println(user);
}
运行结果