從零開始造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);
// 獲取根節(jié)點
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;
}
set和get方法省略
}
獲取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");
}
}
源碼地址:
https://github.com/XWxiaowei/spring-learn/tree/master/liu-spring-demo
作者:碼農(nóng)飛哥
微信公眾號:碼農(nóng)飛哥