从零开始造Spring01---BeanFactory的学习

前言

这是学习刘老师的《从零开始造Spring》的第一篇学习笔记。
主要分为两大块 :
一、解析xml文件,初始化BeanDefinition
二、生成Bean的实例对象
第一堂课比较简单,我们首先从测试用例出发

测试用例

    @Test
    public void testGetBean() {
        // 解析xml文件
        reader.loadBeanDefinitions(new ClassPathResource("petstore-v1.xml"));
        // 获得BeanDefinition
        BeanDefinition bd = factory.getBeanDefinition("petStore");

        assertTrue(bd.isSingleton());

        assertFalse(bd.isPrototype());

        assertEquals(BeanDefinition.SCOPE_DEFAULT,bd.getScope());

        assertEquals("org.litespring.service.v1.PetStoreService",bd.getBeanClassName());

        PetStoreService petStore = (PetStoreService)factory.getBean("petStore");

        assertNotNull(petStore);

        PetStoreService petStore1 = (PetStoreService)factory.getBean("petStore");

        assertTrue(petStore.equals(petStore1));
    }

解析xml 文件

我们是通过XmlBeanDefinitionReader 来解析xml 文件的。采用dom4j的方式解析。核心代码如下:

public void loadBeanDefinitions(Resource resource){
        InputStream is = null;
        try{            
            is = resource.getInputStream();
            SAXReader reader = new SAXReader();
            Document doc = reader.read(is);

            Element root = doc.getRootElement(); //<beans>
            Iterator<Element> iter = root.elementIterator();
            while(iter.hasNext()){
                Element ele = (Element)iter.next();
                String id = ele.attributeValue(ID_ATTRIBUTE);
                String beanClassName = ele.attributeValue(CLASS_ATTRIBUTE);
                BeanDefinition bd = new GenericBeanDefinition(id,beanClassName);
                if (ele.attribute(SCOPE_ATTRIBUTE)!=null) {                 
                    bd.setScope(ele.attributeValue(SCOPE_ATTRIBUTE));                   
                }
                this.registry.registerBeanDefinition(id, bd);
            }
        } catch (Exception e) {     
            throw new BeanDefinitionStoreException("IOException parsing XML document from " + resource.getDescription(),e);
        }finally{
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {                   
                    e.printStackTrace();
                }
            }
        }

    }

注意: Resource类主要是用来获取xml 的文件流,它有两个实现类这里写ClassPathResource 以及FileSystemResource ,第一个实现类主要是获取类路径下的文件,也就是说该xml文件在项目中。第二个实现类主要是用于获取指定路径下的文件。该文件可能不在项目中。

。。。。。。。。。。。。。。。。。

版权原因,完整文章,请参考如下:从零开始造Spring01---BeanFactory的学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值