IoC,用白话来讲,就是由容器控制程序之间的关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
正在业界为IoC争吵不休时,大师级人物Martin Fowler也站出来发话,以一篇经典文章《Inversion of Control Containers and the Dependency Injection pattern》为IoC正名,至此,IoC又获得了一个新的名字:“依赖注入 (Dependency Injection)”。
相对IoC 而言,“依赖注入”的确更加准确的描述了这种古老而又时兴的设计理念。从名字上理解,所谓依赖注入,即组件之间的依赖关系由容器在运行期决定,形象的来说,即由容器动态的将某种依赖关系注入到组件之中。
依赖注入的目标并非为软件系统带来更多的功能,而是为了提升组件重用的概率,并为系统搭建一个灵活、可扩展的平台。
下来看一看一个例子吧!
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是一个配置文件,内容如下:
upperAction=net.yx.spring.qs.UpperAction upperAction_msg=Hello |
UpperAction/LowerAction在运行前,其Message节点为空。运行后由容器将字符串“HeLLo”注入。此时UpperAction/LowerAction即与内存中的“HeLLo”字符串对象建立了依赖关系。
|