1. 程式人生 > >從零開始造Spring00----從XML中讀取Bean並獲取例項

從零開始造Spring00----從XML中讀取Bean並獲取例項

xml的配置

<bean id="petStoreService" class="com.jay.spring.PetStoreService"></bean>

讀取XML

採用dom4j來讀取xml。在工廠類DefaultBeanFactory初始化時就載入xml。程式碼如下:

  SAXReader saxReader = new SAXReader();
                Document document = saxReader.read(inputStream);

//            獲取根節點
                Element rootElement = document.getRootElement
(); Iterator<Element> iterator = rootElement.elementIterator(); while (iterator.hasNext()) { Element element = iterator.next(); String id = element.attributeValue(ID_ATTRIBUTE); String className = element.attributeValue
(CLASS_ATTRIBUTE); BeanDefinition beanDefinition = new BeanDefinition(id, className); beanDefinitionMap.put(id, beanDefinition); }

獲取例項

我們將配置檔案bean中的資訊放在BeanDefinition中,然後將BeanDefinition放在一個全域性的map中,key為id。
BeanDefinition 的實體如下:

public class
BeanDefinition { private String id; private String beanClassName; public BeanDefinition(String id, String beanClassName) { this.id = id; this.beanClassName = beanClassName; } setget方法省略 }

獲取Bean的程式碼如下:

    @Override
    public Object getBean(String id) {
        BeanDefinition bd = getDefinition(id);
        if (bd == null) {
            throw  new BeanException("BeanDefinition is not exist");
        }
        try {
            return Class.forName(bd.getBeanClassName()).newInstance();
        } catch (Exception e) {
            throw new BeanException("bean create exception");
        }
    }

原始碼地址: