模拟spring的IOC

spring提倡的就是面向接口编程,DAO和service都定义为接口。

 

spring中的IOC功能,要在service层中定义dao的实例,当然不用new出来,我们就通过springIOC把这里的dao层注入进来。不要忘了对dao提供setGet方法,因为IOC的底层其实就是利用反射机制实现的,他把dao注入进来,其实底层就是通过反射set进来的。

我们的spring容器——ClassPathXmlApplicationContext:通过这个容器,我们就实现了IOC的功能

  1. public class ClassPathXmlApplicationContext implements BeanFactory {  
  2. private Map<String, Object> beans = new HashMap<String, Object>();  //放配置文件里解析来的一个个bean
  3. public ClassPathXmlApplicationContext() throws Exception, Exception {  
  4. SAXBuilder sb = new SAXBuilder();  
  5. Document doc = sb.build(this.getClass().getClassLoader()  
  6. .getResourceAsStream("beans.xml")); // 构造文档对象   
  7. Element root = doc.getRootElement(); // 获取根元素HD   
  8. List list = root.getChildren("bean");// 取名字为disk的所有元素   
  9. for (int i = 0; i < list.size(); i++) {  
  10. Element element = (Element) list.get(i);  
  11. String id = element.getAttributeValue("id");  
  12. String clazz = element.getAttributeValue("class");  
  13. Object o = Class.forName(clazz).newInstance();  
  14. System.out.println(id);  
  15. System.out.println(clazz);  
  16. beans.put(id, o);  
  17. for (Element propertyElement : (List<Element>) element  
  18. .getChildren("property")) {  
  19. String name = propertyElement.getAttributeValue("name"); // userDAO   
  20. String bean = propertyElement.getAttributeValue("bean"); // u   
  21. Object beanObject = beans.get(bean);// UserDAOImpl instance   
  22. String methodName = "set" + name.substring(01).toUpperCase()  
  23. + name.substring(1);  
  24. System.out.println("method name = " + methodName);  
  25. Method m = o.getClass().getMethod(methodName,  
  26. beanObject.getClass().getInterfaces()[0]);  
  27. m.invoke(o, beanObject);  
  28. }  
  29. }  
  30. }  
  31. @Override  
  32. public Object getBean(String id) {  
  33. return beans.get(id);  
  34. }  
  35. }  

 

SPRING IOC就是我们对象的查找、依赖等,不用我们自己去NEW ,而现在作为配置文件配置在XML中,而spring通过配置文件,遍历所有BEAN,取得bean然后一个一个的newInstance(),和new一样一样的。也就是用到了java的反射原理。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值