IoC,用白話來講,就是由容器控制程序之間的關系,而非傳統(tǒng)實現(xiàn)中,由程序代碼直接操控。這也就是所謂“控制反轉(zhuǎn)”的概念所在:控制權(quán)由應用代碼中轉(zhuǎn)到了外部容器,控制權(quán)的轉(zhuǎn)移,是所謂反轉(zhuǎn)。
正在業(yè)界為IoC爭吵不休時,大師級人物Martin Fowler也站出來發(fā)話,以一篇經(jīng)典文章《Inversion of Control Containers and the Dependency Injection pattern》為IoC正名,至此,IoC又獲得了一個新的名字:“依賴注入 (Dependency Injection)”。
相對IoC 而言,“依賴注入”的確更加準確的描述了這種古老而又時興的設計理念。從名字上理解,所謂依賴注入,即組件之間的依賴關系由容器在運行期決定,形象的來說,即由容器動態(tài)的將某種依賴關系注入到組件之中。
依賴注入的目標并非為軟件系統(tǒng)帶來更多的功能,而是為了提升組件重用的概率,并為系統(tǒng)搭建一個靈活、可擴展的平臺。
下來看一看一個例子吧!
package net.yx.spring.qs;
public interface Action {
public String execute(String str);
}
package net.yx.spring.qs;
public class LowerAction implements Action {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute(String str) {
return (getMessage() + str).toLowerCase();
}
}
package net.yx.spring.qs;
public class UpperAction implements Action {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute(String str) {
return (getMessage() + str).toUpperCase();
}
}
package net.yx.spring.factory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import org.apache.commons.beanutils.BeanUtils;
import net.yx.spring.qs.Action;
/**
* not use spring to implementation AOP
*
* @author Administrator
*
*/
public class ActionFactory {
public static Action getAction(String actionName) {
Properties pro = new Properties();
try {
// load config property file
pro.load(new FileInputStream("config.properties"));
String actionImplName = (String) pro.get(actionName);
String actionMessage = (String) pro.get(actionName + "_msg");
Object obj = Class.forName(actionImplName).newInstance();
BeanUtils.setProperty(obj, "message", actionMessage);
return (Action) obj;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
config.properties是一個配置文件,內(nèi)容如下:
upperAction=net.yx.spring.qs.UpperAction
upperAction_msg=Hello
UpperAction/LowerAction在運行前,其Message節(jié)點為空。運行后由容器將字符串“HeLLo”注入。此時UpperAction/LowerAction即與內(nèi)存中的“HeLLo”字符串對象建立了依賴關系。