分享

spring IoC

 昵称6102701 2014-02-25
控制反转( IoC  =  Inversion  of  Control ),即用容器控制程序间的(关联、继承等)关系。IoC的目标是为了提升组件重用,降低耦合。
下面用一个简单的例子说明其用途。
1、接口:
public interface Action {
public String execute(String msg);
}
2、子类:
public class UpperAction implements Action{

@Override
public String execute(String msg) {
return "Upper : " + msg.toUpperCase();
}

}
public class LowerAction implements Action {

@Override
public String execute(String msg) {
return "Lower : " + msg.toLowerCase();
}

}
3、容器:
import java.util.HashMap;
import java.util.Map;

public class BeanFactory {
private Map<String, String>  mapping = new HashMap<String, String>();
public BeanFactory() {
refresh();
}
/**
* 读取配置文件,缓存所有的bean
*/
private void refresh() {
mapping.put("1", "test.ioc.UpperAction");
mapping.put("2", "test.ioc.LowerAction");
// cacheBean("1", "test.ioc.UpperAction");
// cacheBean("2", "test.ioc.LowerAction");
}

public Object getInstance(String className) {
Class<?> clazz = null;
Object obj = null;
try {
clazz = Class.forName(className);
obj = clazz.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
public Object cacheBean(String id, String className) {
if(!mapping.containsKey(id)) {
mapping.put(id, className);
}
return getInstance(className);
}
public Object getBean(String id) {
Object obj = cacheBean(id, mapping.get(id));
if(obj == null) {
System.out.println("没有找到相关的bean...");
}
return obj;
}
}
4、测试用例:
public class TestCase {

public static void main(String[] args) {
BeanFactory ioc = new BeanFactory();
Action action = (Action) ioc.getBean("1");
System.out.println(action.execute("hahahHHH"));
}

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多