从零开始造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;
}
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
作者:码农飞哥
微信公众号:码农飞哥