模拟Spring控制反转

模拟Spring控制反转IOC

Spring中核心思想控制反转或者称依赖注入
/**
 * 
 * 模拟Spring控制反转
 * @author Administrator
 *
 */
public class ClassPathXmlApplicationContext implements BeanFactory {

    private Map<String , Object> beans = new HashMap<String, Object>();


    //IOC Inverse of Control
    //DI Dependency Injection
    public ClassPathXmlApplicationContext() throws Exception {

        /**
         * 读取所有配置,保存到list中
         */
        SAXBuilder sb=new SAXBuilder();
        Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); //构建文档对象
        Element root=doc.getRootElement(); //获取根元素
        List list=root.getChildren("bean");//获取所有bean子对象

        /**
         * 遍历bean配置,把对象保存中map中
         */
        for(int i=0;i<list.size();i++){
           Element element=(Element)list.get(i);
           String id=element.getAttributeValue("id");
           String clazz=element.getAttributeValue("class");
           Object o = Class.forName(clazz).newInstance();
           System.out.println(id);
           System.out.println(clazz);
           beans.put(id, o);

           /**
            * 当读取到bean中存在property时,把内置对象就setter进去,由于配置关系,我们已经提前放如map中了。
            */
           for(Element propertyElement : (List<Element>)element.getChildren("property")) {
               String name = propertyElement.getAttributeValue("name"); //userDAO
               String bean = propertyElement.getAttributeValue("bean"); //u
               Object beanObject = beans.get(bean);//UserDAOImpl instance

               String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
               System.out.println("method name = " + methodName);

               Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
               m.invoke(o, beanObject);
           }


        }  

    }



    public Object getBean(String id) {
        return beans.get(id);
    }

}

配置文件如下。

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="u" class="cn.simplemang.spring.dao.impl.UserDAOImpl" />
    <bean id="userService" class="cn.simplemang.spring.service.UserService">
        <property name="userDAO" bean="u"/>
    </bean>
</beans>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值