从零开始造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文件在项目中。第二个实现类主要是用于获取指定路径下的文件。该文件可能不在项目中。

public interface Resource {
    public InputStream getInputStream() throws IOException;
    public String getDescription();
}

生成Bean的实例

首先,传入getBean方法传入beanID,在该方法中 首先拿到BeanDefinition,然后,根据beanClassName 字段通过反射的方式生成对应的bean 实例。
核心代码如下:

    public Object getBean(String beanID) {
        BeanDefinition bd = this.getBeanDefinition(beanID);
        if(bd == null){
            return null;
        }
        //bd是单例
        if(bd.isSingleton()){
            Object bean = this.getSingleton(beanID);
            if(bean == null){
                bean = createBean(bd);
                this.registerSingleton(beanID, bean);
            }
            return bean;
        } 
        return createBean(bd);
    }
    private Object createBean(BeanDefinition bd) {
        ClassLoader cl = this.getBeanClassLoader();
        String beanClassName = bd.getBeanClassName();
        try {
            Class<?> clz = cl.loadClass(beanClassName);
            return clz.newInstance();
        } catch (Exception e) {         
            throw new BeanCreationException("create bean for "+ beanClassName +" failed",e);
        }   
    }

其中,DefaultSingletonBeanRegistry 类中定义了一个ConcurrentHashMap,将生成bean实例放在该Map中,在调用registerSingleton方法时,首先会根据beanName检查是否已存在实例,如果存在在抛出异常。否则,将新生成的实例放入该Map中。

    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);

    public void registerSingleton(String beanName, Object singletonObject) {

        Assert.notNull(beanName, "'beanName' must not be null");

        Object oldObject = this.singletonObjects.get(beanName);
        if (oldObject != null) {
            throw new IllegalStateException("Could not register object [" + singletonObject +
                    "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
        }
        this.singletonObjects.put(beanName, singletonObject);

    }

    public Object getSingleton(String beanName) {

        return this.singletonObjects.get(beanName);
    }

源代码:刘老师的源码地址


作者:码农飞哥

微信公众号:码农飞哥