DI/IOC概述:
依賴注入/控制反轉。某一個類中需要使用其他類中的方法來實現業務時,一般採用在前者中聲明後者並實例化,然後用後者的實例在前者中調用後者的方法,這種情形下,前者依賴後者,被依賴類的對象生滅由依賴類控制,這種做法耦合度較高。在使用spring的情形下,通過反射機制,類統一在spring中註冊,被依賴對象統一由spring注入到依賴對象中。依賴注入和控制反轉是站在不同的角度對同一動作的不同描述,DI,被依賴對象由spring容器實例化並注入到依賴對象中,IOC,被依賴對象的生滅由依賴對象控制轉換爲spring容器。
案例:
有三個類,Iron(鐵),Axe(斧子),HumanBeing(人類),人類類依賴斧子類,斧子類依賴鐵類。
Iron:
package com.sunsharing.di;
/**
* Created by baich on 2016/1/22.
*/
public class Iron {
public void useage() {
System.out.println("Iron used to make tools");
}
}
Axe:
package com.sunsharing.di;
/**
* Created by baich on 2016/1/22.
*/
public class Axe {
private Iron iron;
public Iron getIron() {
return iron;
}
public void setIron(Iron iron) {
this.iron = iron;
}
public void cut() {
iron.useage();
System.out.println("cut tree!");
}
}
HumanBeing:
package com.sunsharing.di;
/**
* Created by baich on 2016/1/22.
*/
public class HumanBeing {
private Axe axe;
public Axe getAxe() {
return axe;
}
public void setAxe(Axe axe) {
this.axe = axe;
}
public void useAxe() {
axe.cut();
}
}
配置文件bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="Iron" class="com.sunsharing.di.Iron"></bean>
<bean id="Axe" class="com.sunsharing.di.Axe">
<property name="Iron" ref="Iron"/>
</bean>
<bean id="HumanBeing" class="com.sunsharing.di.HumanBeing">
<property name="Axe" ref="Axe"/>
</bean>
</beans>
spring引擎SpringEngin:
package com.sunsharing.di;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Method;
import java.util.List;
/**
* Created by baich on 2016/1/22.
*/
public class SpringEngin {
/**
* 遞歸獲取對象
* @param ele 父節點
* @param className bean id值
* @return
*/
public Object getObj(Element ele, String className) throws Exception {
List<Element> elements = ele.elements("bean");
for (Element element : elements) {
Attribute atb = element.attribute("id");
String idV = atb.getValue();
if(idV.equals(className)) {
Attribute atb02 = element.attribute("class");
String classV = atb02.getValue();
Object obj = Class.forName(classV).newInstance();
List<Element> eleList = element.elements("property");
for (Element el : eleList) {
Attribute atb03 = el.attribute("name");
String nV = atb03.getValue();
Attribute atb04 = el.attribute("ref");
String refV = atb04.getValue();
Object ob = getObj(ele, refV);
Method mt = obj.getClass().getMethod("set" + nV, ob.getClass());
mt.invoke(obj, ob);
}
return obj;
}
}
return null;
}
/**
*
* @param className 待實例化的類
* @return
* @throws Exception
*/
public Object getObj(String className) throws Exception {
SAXReader reader = new SAXReader();
File file = new File("bean.xml");
Document document = reader.read(file);
Element root = document.getRootElement();
Object obj = getObj(root, className);
return obj;
}
public static void main(String[] args) throws Exception {
SpringEngin se = new SpringEngin();
HumanBeing hb = (HumanBeing) se.getObj("HumanBeing");
hb.useAxe();
}
}