2.动手写简版spring之IOC解耦篇

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 方法中调用 beanfactoryregisterBeanDefinition 方法。
  • SimpleBeanFactory 类实现了 Beanfactory 接口,提供了 getBeanregisterBeanDefinition 方法的具体实现。
  • ClassPathXmlResource 类实现了 Resource 接口,用于从指定的 XML 文件中读取元素信息。
  • ClassPathXmlApplicationContext 类在构造函数中创建了 ClassPathXmlResourceSimpleBeanFactoryXmlBeanDefinitionReader 对象,并通过 XmlBeanDefinitionReader 加载 XML 中的 bean 定义到 SimpleBeanFactory 中。同时,提供了 getBeanregisterBeanDefinition 方法。
  • 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟空学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值