文章目录
0、目标
动作写简版spring之IOC篇的重构,将原有的ClassPathXmlApplicationContext
类拆分多个类。让职责清晰。
1、核心原理
原有的ClassPathXmlApplicationContext
大包大揽,现在只让它做一个组织管理者,具体的工作交给专业的对象。
1、xml文件被抽象为ClassPathXmlResource
(还给它配了一个接口Resource)。
2、定义一个框子SimpleBeanFactory
( 还给它配了一个接口Beanfactory ),给出配置信息,能够获取bean(懒加载)。
3、读取xml的事情,交给XmlBeanDefinitionReader
,它负责读取Resource
后把Bean
的定义配置传给Beanfactory
。
2、类与类之间关系
这些类之间的关联关系如下:
XmlBeanDefinitionReader
类依赖Beanfactory
类,通过构造函数接收Beanfactory
对象,并在loadBeanDefinitions
方法中调用beanfactory
的registerBeanDefinition
方法。SimpleBeanFactory
类实现了Beanfactory
接口,提供了getBean
和registerBeanDefinition
方法的具体实现。ClassPathXmlResource
类实现了Resource
接口,用于从指定的 XML 文件中读取元素信息。ClassPathXmlApplicationContext
类在构造函数中创建了ClassPathXmlResource
、SimpleBeanFactory
和XmlBeanDefinitionReader
对象,并通过XmlBeanDefinitionReader
加载 XML 中的 bean 定义到SimpleBeanFactory
中。同时,提供了getBean
和registerBeanDefinition
方法。Main
类使用ClassPathXmlApplicationContext
来获取 bean 对象。
总的来说,这些类协同工作,实现了一个简单的基于 XML 配置的 IoC 容器的功能。
2.1 BeanDefinition
封装基础配置信息
public class BeanDefinition {
private String id,className;
public BeanDefinition(String id, String className) {
this.id = id;
this.className = className;
}
……
2.2 BeanException
自定义异常
public class BeanException extends Exception {
public BeanException(String message) {
super(message);
}
}
2.3 ClassPathXmlResource
Resource 接口
public interface Resource extends Iterator<Object> {
}
ClassPathXmlResource 类
public class ClassPathXmlResource implements Resource {
private Document document;
private Element rootElement;
private Iterator<Element> elementIterator;
public ClassPathXmlResource(String filename) {
SAXReader saxReader = new SAXReader