前言
一、IOC是什么?
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。
二、IOC的实现
1.引入库
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Hashtable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
2.主要实现
// 定义容器
private Hashtable<String, Object> hash = new Hashtable<String, Object>();
public void init(String fileName) throws ParserConfigurationException, SAXException, IOException,
InstantiationException, IllegalAccessException, ClassNotFoundException {
/**
* 获取xml转为文档
*/
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File(fileName)));// 解析出xml变文档
Node root = doc.getDocumentElement();// 得到根节点
NodeList childList = root.getChildNodes();// 获取根的孩子结点
for (int i = 0; i < childList.getLength(); i++) {
Node childNode = childList.item(i);// 获取孩子索引值
// noteAttriute不为空,当值不为空
// Node是w3c的包
NamedNodeMap noteAttriute = childNode.getAttributes();// 获取节点的属性
// if是为了空值的的出现
if (noteAttriute != null) {
Node clazz = noteAttriute.getNamedItem("class");// 获取指定名字的节点
Node id = noteAttriute.getNamedItem("id");
if (clazz != null && id != null) {
String className = clazz.getNodeValue();// 获取指定节点的值
String idName = id.getNodeValue();
System.out.println(className);
System.out.println(idName);
// 依据配置文件,将实例对象加入容器
Object o1 = Class.forName(className).newInstance();
hash.put(idName, o1);
}
}
}
}
// 获取bean对象
public Object getBean(String id) throws IllegalArgumentException, IllegalAccessException {
Object obj = hash.get(id);// 由id获取实例化对象
Field[] fies = obj.getClass().getDeclaredFields();// 获取属性
for (Field d : fies) {
if (d.isAnnotationPresent(AutoWired.class)) {
d.setAccessible(true);
d.set(obj, hash.get(d.getName()));//obj表示属性被修改的对象
}
}
return obj;
}
总结
通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。通过IOC的技术,可以大范围省去new对象的时间,大大提高程序的执行效率,并且反射机制和集合的良好应用,也是IOC的一大亮点。