设计模式_自定义Spring框架(IOC)

设计模式_自定义Spring框架(IOC)

笔记整理自 黑马程序员Java设计模式详解, 23种Java设计模式(图解+框架源码分析+实战)

Spring使用回顾

自定义spring 框架前,先回顾一下 Spring 框架的使用,从而分析 Spring 的核心,并对核心功能进行模拟。

  • 数据访问层。定义 UserDao 接口及其子实现类

    public interface UserDao {
          
          
        public void add();
    }
    
    public class UserDaoImpl implements UserDao {
          
          
    
        public void add() {
          
          
            System.out.println("UserDao ...");
        }
    }
    
  • 业务逻辑层。定义 UserService 接口及其子实现类

    public interface UserService {
          
          
        public void add();
    }
    
    public class UserServiceImpl implements UserService {
          
          
    
        private UserDao userDao;
    
        public void setUserDao(UserDao userDao) {
          
          
            this.userDao = userDao;
        }
    
        public void add() {
          
          
            System.out.println("UserService ...");
            userDao.add();
        }
    }
    
  • 定义 UserController 类,使用 main 方法模拟 controller 层

    public class UserController {
          
          
        public static void main(String[] args) {
          
          
            // 1.创建spring容器对象
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            // 2.从IOC容器中获取UserService对象
            UserService userService = applicationContext.getBean("userService", UserService.class);
            // 3.调用UserService对象的add方法 进行业务处理
            userService.add();
        }
    }
    
  • 编写配置文件。在类路径下编写一个名为 applicationContext.xml 的配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
            <property name="userDao" ref="userDao"></property>
        </bean>
    
        <bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
    
    </beans>
    

    代码运行结果如下:

    image-20230110120208942

通过上面代码及结果可以看出:

  • userService 对象是从 applicationContext 容器对象获取到的,也就是 userService 对象交由 Spring 进行管理。
  • 上面结果可以看到调用了 UserDao 对象中的 add 方法,也就是说 UserDao 子实现类对象也交由 Spring 管理了。
  • UserService 中的 userDao 变量我们并没有进行赋值,但是可以正常使用,说明 Spring 已经将 UserDao 对象赋值给了 userDao 变量。

上面三点体现了 Spring 框架的 IOC(Inversion of Control)和 DI(Dependency Injection, DI)

Spring核心功能结构

Spring 大约有 20 个模块,由 1300 多个不同的文件构成。这些模块可以分为:

核心容器、AOP 和设备支持、数据访问与集成、Web 组件、通信报文和集成测试等,下面是 Spring 框架的总体架构图:

核心容器由 beans、core、context 和 expression(Spring Expression Language,SpEL)4 个模块组成。

  • spring-beans 和 spring-core 模块是 Spring 框架的核心模块,包含了控制反转(Inversion of Control,IOC)和依赖注入(Dependency Injection,DI)。BeanFactory 使用控制反转对应用程序的配置和依赖性规范与实际的应用程序代码进行了分离。BeanFactory 属于延时加载,也就是说在实例化容器对象后并不会自动实例化 Bean,只有当 Bean 被使用时,BeanFactory 才会对该 Bean 进行实例化与依赖关系的装配。
  • spring-context 模块构架于核心模块之上,扩展了 BeanFactory,为它添加了 Bean 生命周期控制、框架事件体系及资源加载透明化等功能。此外,该模块还提供了许多企业级支持,如邮件访问、远程访问、任务调度等,ApplicationContext 是该模块的核心接口,它的超类是 BeanFactory。与 BeanFactory 不同,ApplicationContext 实例化后会自动对所有的单实例 Bean 进行实例化与依赖关系的装配,使之处于待用状态。
  • spring-context-support 模块是对 Spring IoC 容器及 IoC 子容器的扩展支持。
  • spring-context-indexer 模块是 Spring 的类管理组件和 Classpath 扫描组件。
  • spring-expression 模块是统一表达式语言(EL)的扩展模块,可以查询、管理运行中的对象,同时也可以方便地调用对象方法,以及操作数组、集合等。它的语法类似于传统 EL,但提供了额外的功能,最出色的要数函数调用和简单字符串的模板函数。EL的特性是基于 Spring 产品的需求而设计的,可以非常方便地同 Spring IoC 进行交互。

bean概述

Spring 就是面向 Bean 的编程(BOP,Bean Oriented Programming),Bean 在 Spring 中处于核心地位。Bean 对于 Spring 的意义就像 Object 对于 OOP 的意义一样,Spring 中没有 Bean 也就没有 Spring 存在的意义。Spring IoC 容器通过配置文件或者注解的方式来管理 bean 对象之间的依赖关系。

Spring 中 bean 用于对一个类进行封装。如下面的配置:

<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
    <property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>

为什么 Bean 如此重要呢?

  • Spring 将 bean 对象交由一个叫 IOC 容器进行管理。
  • bean 对象之间的依赖关系在配置文件中体现,并由 Spring 完成。

Spring IOC相关接口分析

BeanFactory解析

Spring 中 Bean 的创建是典型的工厂模式,这一系列的 Bean 工厂,即 IoC 容器,为开发者管理对象之间的依赖关系提供了很多便利和基础服务,在 Spring 中有许多 IoC 容器的实现供用户选择,其相互关系如下图所示。

其中,BeanFactory 作为最顶层的一个接口,定义了 IoC 容器的基本功能规范,BeanFactory 有三个重要的子接口:

  • ListableBeanFactory
  • HierarchicalBeanFactory
  • AutowireCapableBeanFactory

但是从类图中我们可以发现最终的默认实现类是 DefaultListableBeanFactory,它实现了所有的接口。

那么为何要定义这么多层次的接口呢?

每个接口都有它的使用场合,主要是为了区分在 Spring 内部操作过程中对象的传递和转化,对对象的数据访问所做的限制。例如,

  • ListableBeanFactory 接口表示这些 Bean 可列表化(可以通过列表的方式对 Bean 对象进行存储)。
  • HierarchicalBeanFactory 表示这些 Bean 是有继承关系的,也就是每个 Bean 可能有父 Bean。
  • AutowireCapableBeanFactory 接口定义 Bean 的自动装配规则。

这三个接口共同定义了 Bean 的集合、Bean 之间的关系及 Bean 行为。最基本的 IoC 容器接口是 BeanFactory,来看一下它的源码:

public interface BeanFactory {
    
    

	String FACTORY_BEAN_PREFIX = "&";

	// 根据bean的名称获取IOC容器中的的bean对象
	Object getBean(String name) throws BeansException;
	// 根据bean的名称获取IOC容器中的的bean对象,并指定获取到的bean对象的类型,这样我们使用时就不需要进行类型强转了
	<T> T getBean(String name, Class<T> requiredType) throws BeansException;
	Object getBean(String name, Object... args) throws BeansException;
	<T> T getBean(Class<T> requiredType) throws BeansException;
	<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
	
	<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
	<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);

	// 判断容器中是否包含指定名称的bean对象
	boolean containsBean(String name);
	// 根据bean的名称判断是否是单例
	boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
	boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
	boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
	boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
	@Nullable
	Class<?> getType(String name) throws NoSuchBeanDefinitionException;
	String[] getAliases(String name);
}

在 BeanFactory 里只对 IoC 容器的基本行为做了定义,根本不关心你的Bean是如何定义及怎样加载的。正如我们只关心能从工厂里得到什么产品,不关心工厂是怎么生产这些产品的。

BeanFactory 有一个很重要的子接口,就是 ApplicationContext 接口,该接口主要来规范容器中的 bean 对象是非延时加载,即在创建容器对象的时候就对象 bean 进行初始化,并存储到一个容器中。

要知道工厂是如何产生对象的,我们需要看具体的 IoC 容器实现,Spring 提供了许多 IoC 容器实现,比如:

  • ClasspathXmlApplicationContext:根据类路径加载xml配置文件,并创建 IOC 容器对象。
  • FileSystemXmlApplicationContext:根据系统路径加载xml配置文件,并创建 IOC 容器对象。
  • AnnotationConfigApplicationContext:加载注解类配置,并创建 IOC 容器。

BeanDefinition解析

Spring IoC 容器管理我们定义的各种 Bean 对象及其相互关系,而 Bean 对象在 Spring 实现中是以 BeanDefinition 来描述的,如下面配置文件

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>

bean标签还有很多属性:
	scope、init-method、destory-method等。

其继承体系如下图所示:

BeanDefinitionReader解析

Bean 的解析过程非常复杂,功能被分得很细,因为这里需要被扩展的地方很多,必须保证足够的灵活性,以应对可能的变化。Bean 的解析主要就是对 Spring 配置文件的解析。这个解析过程主要通过 BeanDefinitionReader 来完成,看看 Spring 中 BeanDefinitionReader 的类结构图,如下图所示:

上图只是部分结构,我们可以看到 BeanDefinitionReader 的子实现类有 PropertiesXml,PropertiesBeanDefinitionReader 就是专门解析 .properties 的配置文件,但我们大多数用的都是 XmlBeanDefinitionReader 来解析 .xml 的配置文件。

image-20230110153834330

看看 BeanDefinitionReader 接口定义的功能来理解它具体的作用:

public interface BeanDefinitionReader {
    
    

	// 获取BeanDefinitionRegistry注册器对象
	BeanDefinitionRegistry getRegistry();

	@Nullable       

	@Nullable
	ClassLoader getBeanClassLoader();

	BeanNameGenerator getBeanNameGenerator();

	/*
	 * 下面的loadBeanDefinitions都是加载bean定义,从指定的资源(配置文件)中,封装成BeanDefinition对象
	 */
	int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException;
	int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException;
	int loadBeanDefinitions(String location) throws BeanDefinitionStoreException;
	int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException;
}

BeanDefinitionRegistry解析

BeanDefinitionReader 用来解析 bean 定义,并封装 BeanDefinition 对象,而我们定义的配置文件中定义了很多 bean 标签,所以就有一个问题,解析的 BeanDefinition 对象存储到哪儿?答案就是 BeanDefinition 的注册中心,而该注册中心顶层接口就是 BeanDefinitionRegistry。

public interface BeanDefinitionRegistry extends AliasRegistry {
    
    

	// 往注册表中注册bean
	void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException;

	// 从注册表中删除指定名称的bean
	void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

	// 获取注册表中指定名称的bean
	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
    
	// 判断注册表中是否已经注册了指定名称的bean
	boolean containsBeanDefinition(String beanName);
    
	// 获取注册表中所有的bean的名称
	String[] getBeanDefinitionNames();
    
	int getBeanDefinitionCount();
	boolean isBeanNameInUse(String beanName);
}

继承结构图如下:

从上面类图可以看到 BeanDefinitionRegistry 接口的子实现类主要有以下几个:

  • SimpleBeanDefinitionRegistry

    它就是一个简单的 BeanDefinition 的注册中心,由于解析出来的 BeanDefinition 对象就存储在 BeanDefinition 的注册中心,所以它必然是一个容器。这个类更需要关注。

    在该类中定义了如下代码,就是用来注册 bean:

    private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(64);
    
  • DefaultListableBeanFactory

    该类不仅实现了 BeanFactory 接口,还实现了 BeanDefinitionRegistry 接口,所以该类既是容器,也是注册表。

    在该类中定义了如下代码,就是用来注册 bean:

    private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
    
  • GenericApplicationContext

    该类间接地实现了 ApplicationContext 接口,所以它既是容器,也是注册表。

创建容器

我们查看 ClassPathXmlApplicationContext 这个容器类的源码来简单分析一下创建容器的过程:

public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
    
    
    
    // 无参构造方法
    public ClassPathXmlApplicationContext() {
    
    
    }

    // 再传入一个ApplicationContext对象,即父容器
    public ClassPathXmlApplicationContext(ApplicationContext parent) {
    
    
       super(parent);
    }

    /*
     * 我们创建ClassPathXmlApplicationContext时,一般都传递的是一个字符串,就是使用的这个构造方法
     * configLocation:就是类路径下面的配置文件的路径
     * 它底层又套娃的另一个构造方法
     */
    public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
    
    
       this(new String[] {
    
    configLocation}, true, null);
    }
    	||
        \/
    /*
     * @param
     * String[] configLocations:配置文件位置
     * boolean refresh:上面的构造方法传入 refresh值固定为true
     * ApplicationContext parent:上面的构造方法传入 父容器固定为null
     */
    public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {
    
    

		super(parent);
		setConfigLocations(configLocations);
        // 判断refresh是否为true 在此逻辑中必定满足 进入if
		if (refresh) {
    
    
            // 真正的核心就是这个 refresh 方法
			refresh();
		}
	}

refresh()

    // 父类AbstractApplicationContext中的方法
	@Override
    public void refresh() throws BeansException, IllegalStateException {
    
    
       synchronized (this.startupShutdownMonitor) {
    
    
          StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

          // Prepare this context for refreshing. 准备此容器以进行刷新。
          prepareRefresh(); // #1 准备刷新上下文环境

          // Tell the subclass to refresh the internal bean factory. 告诉子类刷新内部bean工厂。
          ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // #2 初始化BeanFactory 并加载bean definitions信息

          // Prepare the bean factory for use in this context. 准备用于此容器的bean工厂。
          prepareBeanFactory(beanFactory); // #3 对beanFacotry进行配置

          try {
    
    
             // Allows post-processing of the bean factory in context subclasses. 允许在容器子类中对bean工厂进行后处理。
             postProcessBeanFactory(beanFactory); // #4 提供给子类扩展的预留方法

             StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
             // Invoke factory processors registered as beans in the context. 在容器中调用注册为bean的工厂处理器。
             invokeBeanFactoryPostProcessors(beanFactory); // #5 激活BeanFactoryPostProcessors

             // Register bean processors that intercept bean creation. 注册拦截bean创建的bean处理器。
             registerBeanPostProcessors(beanFactory);  // #6 注册BeanPostProcessors
             beanPostProcess.end();

             // Initialize message source for this context. 初始化此容器的消息源。
             initMessageSource(); // #7 初始化MessageSource

             // Initialize event multicaster for this context. 为此容器初始化事件多播。
             initApplicationEventMulticaster(); // #8 初始化事件广播器

             // Initialize other special beans in specific context subclasses. 初始化特定容器子类中的其他特殊bean。
             onRefresh(); // #9 提供给子类初始化其他的Bean

             // Check for listener beans and register them. 检查侦听器bean并注册它们。
             registerListeners(); // #10 注册事件监听器

             // Instantiate all remaining (non-lazy-init) singletons. 实例化所有剩余的(非惰性初始化)单例。
             finishBeanFactoryInitialization(beanFactory); // #11 构造热加载单例bean

             // Last step: publish corresponding event. 最后一步:发布相应的事件。
             finishRefresh(); // #12 完成刷新过程,通知生命周期处理器
          }

          catch (BeansException ex) {
    
    
             if (logger.isWarnEnabled()) {
    
    
                logger.warn("Exception encountered during context initialization - " +
                      "cancelling refresh attempt: " + ex);
             }

             // Destroy already created singletons to avoid dangling resources. 销毁已创建的单实例以避免悬空资源。
             destroyBeans(); // #13 出错了,销毁bean

             // Reset 'active' flag. 重置“激活”标志。
             cancelRefresh(ex); // #14 出错了,修改active标识

             // Propagate exception to caller. 向调用方传播异常。
             throw ex;
          }

          finally {
    
    
             // Reset common introspection caches in Spring's core, since we  重置Spring核心中的常见内省缓存,因为我们
             // might not ever need metadata for singleton beans anymore...   可能不再需要单例bean的元数据...
             resetCommonCaches();
             contextRefresh.end();
          }
       }
    }

refresh() 方法做了非常多的事情,简要概括:refresh 方法做的事就是加载配置文件并去初始化 Bean 对象,然后将 Bean 对象存储在容器里面。

我们平时常说的 Spring 启动其实就是调用 AbstractApplicationContext#refresh 完成 spring context 的初始化和启动过程。spring context 初始化从开始到最后结束以及启动,这整个过程都在 refresh 这个方法中。refresh 方法刚开始做的是一些 spring context 的准备工作,也就是 spring context 的初始化,比如:创建 BeanFactory、注册 BeanFactoryPostProcessor 等,只有等这些准备工作做好以后才去开始 spring context 的启动。

总结:

ClassPathXmlApplicationContext 对 Bean 配置资源的载入是从 refresh() 方法开始的。refresh() 方法是一个模板方法,规定了 IoC 容器的启动流程,有些逻辑要交给其子类实现。它对 Bean 配置资源进行载入,ClassPathXmlApplicationContext 通过调用其父类 AbstractApplicationContext 的 refresh() 方法启动整个 IoC 容器对 Bean 定义的载入过程。

自定义Spring IOC

现要对下面的配置文件进行解析,并自定义 Spring 框架的 IOC 对涉及到的对象进行管理。

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
    <bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
</beans>

整体架构

image-20230110223722425

定义bean相关的pojo类

PropertyValue类

用于封装 bean 的属性,体现到上面的配置文件就是封装 bean 标签的子标签 property 标签数据。

/**
 * 用来封装bean标签下的property标签的属性
 * name属性
 * ref属性
 * value属性:给基本数据类型及String类型数据赋的值
 */
public class PropertyValue {
    
    

  	private String name;
  	private String ref;
  	private String value;

  	public PropertyValue() {
    
    
  	}

  	public PropertyValue(String name, String ref, String value) {
    
    
    	this.name = name;
    	this.ref = ref;
    	this.value = value;
  	}

  	public String getName() {
    
    
    	return name;
  	}

  	public void setName(String name) {
    
    
    	this.name = name;
  	}

  	public String getRef() {
    
    
    	return ref;
  	}

  	public void setRef(String ref) {
    
    
    	this.ref = ref;
  	}

  	public String getValue() {
    
    
    	return value;
  	}

  	public void setValue(String value) {
    
    
    	this.value = value;
  	}
}

MutablePropertyValues类

一个 bean 标签可以有多个 property 子标签,所以再定义一个 MutablePropertyValues 类,用来存储并管理多个 PropertyValue 对象。

使用了迭代器模式

/**
 * 用来存储和管理多个PropertyValue对象
 */
public class MutablePropertyValues implements Iterable<PropertyValue> {
    
    

    // 定义list集合对象,用来存储PropertyValue对象
    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
    
    
        this.propertyValueList = new ArrayList<PropertyValue>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
    
    
        this.propertyValueList = (propertyValueList != null ? propertyValueList : new ArrayList<PropertyValue>());
    }

    // 获取所有的PropertyValue对象,返回以数组的形式
    public PropertyValue[] getPropertyValues() {
    
    
        // 将集合转换为数组并返回
        return this.propertyValueList.toArray(new PropertyValue[0]);
    }

    // 根据name属性值获取PropertyValue对象
    public PropertyValue getPropertyValue(String propertyName) {
    
    
        // 遍历集合对象
        for (PropertyValue pv : this.propertyValueList) {
    
    
            if (pv.getName().equals(propertyName)) {
    
    
                return pv;
            }
        }
        return null;
    }

    // 获取迭代器对象
    @Override
    public Iterator<PropertyValue> iterator() {
    
    
        return propertyValueList.iterator();
    }

    // 判断集合是否为空
    public boolean isEmpty() {
    
    
        return this.propertyValueList.isEmpty();
    }

    // 添加PropertyValue对象
    public MutablePropertyValues addPropertyValue(PropertyValue pv) {
    
    
        // 判断集合中存储的PropertyValue对象是否和传递进行的重复了,如果重复了,进行覆盖
        for (int i = 0; i < this.propertyValueList.size(); i++) {
    
    
            // 获取集合中每一个PropertyValue对象
            PropertyValue currentPv = this.propertyValueList.get(i);
            if (currentPv.getName().equals(pv.getName())) {
    
    
                this.propertyValueList.set(i, new PropertyValue(pv.getName(), pv.getRef(), pv.getValue()));
                return this; // 目的就是实现链式编程
            }
        }
        this.propertyValueList.add(pv);
        return this; // 目的就是实现链式编程
    }

    // 判断是否有指定name属性值的对象
    public boolean contains(String propertyName) {
    
    
        return getPropertyValue(propertyName) != null;
    }
}

实际在 Spring 中确实有一个 PropertyValue 类,但还有一个接口:PropertyValues,它继承了 Iterable 接口,重写了迭代器的一些方法,且 MutablePropertyValues 类实现了 PropertyValues 接口。

public interface PropertyValues extends Iterable<PropertyValue> {
     
     
}

public class MutablePropertyValues implements PropertyValues, Serializable {
     
     

	private final List<PropertyValue> propertyValueList;
}

BeanDefinition类

BeanDefinition 类用来封装 bean 信息的,主要包含 id(即 bean 对象的名称)、class(需要交由 Spring 管理的类的全类名)及子标签 property 数据。

/**
 * 用来封装bean标签数据
 * id属性
 * class属性
 * property子标签的数据
 */
public class BeanDefinition {
    
    
    private String id;
    private String className;

    private MutablePropertyValues propertyValues;

    public BeanDefinition() {
    
    
        propertyValues = new MutablePropertyValues();
    }

    public String getId() {
    
    
        return id;
    }

    public void setId(String id) {
    
    
        this.id = id;
    }

    public String getClassName() {
    
    
        return className;
    }

    public void setClassName(String className) {
    
    
        this.className = className;
    }

    public void setPropertyValues(MutablePropertyValues propertyValues) {
    
    
        this.propertyValues = propertyValues;
    }

    public MutablePropertyValues getPropertyValues() {
    
    
        return propertyValues;
    }
}

定义注册表相关类

BeanDefinitionRegistry接口

BeanDefinitionRegistry 接口定义了注册表的相关操作,定义如下功能:

  • 注册 BeanDefinition 对象到注册表中
  • 从注册表中删除指定名称的 BeanDefinition 对象
  • 根据名称从注册表中获取 BeanDefinition 对象
  • 判断注册表中是否包含指定名称的 BeanDefinition 对象
  • 获取注册表中 BeanDefinition 对象的个数
  • 获取注册表中所有的 BeanDefinition 的名称
// 注册表对象
public interface BeanDefinitionRegistry {
    
    

    // 注册BeanDefinition对象到注册表中
    void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);

    // 从注册表中删除指定名称的BeanDefinition对象
    void removeBeanDefinition(String beanName) throws Exception;

    // 根据名称从注册表中获取BeanDefinition对象
    BeanDefinition getBeanDefinition(String beanName) throws Exception;

    boolean containsBeanDefinition(String beanName);

    int getBeanDefinitionCount();

    String[] getBeanDefinitionNames();
}

SimpleBeanDefinitionRegistry类

该类实现了 BeanDefinitionRegistry 接口,定义了 Map 集合作为注册表容器。

// 注册表接口子实现类
public class SimpleBeanDefinitionRegistry implements BeanDefinitionRegistry {
    
    

    // 定义一个容器,用来存储BeanDefinition对象
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<String, BeanDefinition>();

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
    
    
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public void removeBeanDefinition(String beanName) throws Exception {
    
    
        beanDefinitionMap.remove(beanName);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws Exception {
    
    
        return beanDefinitionMap.get(beanName);
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
    
    
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public int getBeanDefinitionCount() {
    
    
        return beanDefinitionMap.size();
    }

    @Override
    public String[] getBeanDefinitionNames() {
    
    
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }
}

定义解析器相关类

BeanDefinitionReader接口

为什么我们还要创建 BeanDefinitionReader 接口呢?之前分析 Spring IoC 功能相关的接口时,针对于不同的配置文件,Spring 会提供不同的子类来进行解析。例如,解析properties 格式的配置文件用的是 PropertiesBeanDefinitionReader 类,解析 ``xml` 格式的配置文件用的是 XmlBeanDefinitionReader。在 BeanDefinitionReader 接口的继承体系中这两个类都是其子实现类。

这里我们在自定义 Spring IoC 功能时,只会针对 xml 格式的配置文件来创建解析类。

BeanDefinitionReader 是用来解析配置文件并在注册表中注册 bean 的信息。定义了两个规范:

  • 获取注册表的功能,让外界可以通过该对象获取注册表对象。
  • 加载配置文件,并注册 bean 数据。
// 用来解析配置文件的,而该接口只是定义了规范
public interface BeanDefinitionReader {
    
    

	// 获取注册表对象
    BeanDefinitionRegistry getRegistry();
    
	// 加载配置文件并在注册表中进行注册
    void loadBeanDefinitions(String configLocation) throws Exception;
}

XmlBeanDefinitionReader类

XmlBeanDefinitionReader 类是专门用来解析 xml 配置文件的。该类实现 BeanDefinitionReader 接口并实现接口中的两个功能。

// 针对xml配置文件进行解析的类
public class XmlBeanDefinitionReader implements BeanDefinitionReader {
    
    

    /*
     * 声明注册表对象
     * 为什么要在成员变量位置处声明注册表对象呢?
     * XmlBeanDefinitionReader对象(即解析器)是专门用来解析XML格式的配置文件的,
     * 解析完之后,自然是会将配置文件里面的<bean>标签封装成BeanDefinition对象,这些BD对象最终都要存放到注册表中。
     */
    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
    
    
        this.registry = new SimpleBeanDefinitionRegistry();
    }

    // 获取注册表对象
    @Override
    public BeanDefinitionRegistry getRegistry() {
    
    
        return registry;
    }

    /*
     * 加载配置文件,并在注册表中进行注册
     * @param configLocation 类路径下配置文件的路径
     */
    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
    
    
        // 获取类路径下的配置文件。注意,这里我们只实现类路径下的配置文件的加载
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(configLocation);
        // 使用dom4j进行xml配置文件的解析(需要在pom.xml导入对应的jar包)
        SAXReader reader = new SAXReader();
        Document document = reader.read(is);
        // 根据Document对象获取根标签对象(根标签很明显就是<beans>标签)
        Element rootElement = document.getRootElement();
        /*
         * 解析bean标签
         */
        // 获取根标签下所有的<bean>子标签对象
        List<Element> beanElements = rootElement.elements("bean");
        // 遍历集合
        for (Element beanElement : beanElements) {
    
    
            // 获取id属性
            String id = beanElement.attributeValue("id");
            // 获取class属性
            String className = beanElement.attributeValue("class");

            // 将id属性和class属性封装到BeanDefinition对象中
            // 1.创建BeanDefinition对象
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);

            // 2.创建MutablePropertyValues对象
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();

            // 3.获取<bean>标签下所有的<property>子标签对象
            List<Element> propertyElements = beanElement.elements("property");
            for (Element propertyElement : propertyElements) {
    
    
                String name = propertyElement.attributeValue("name");
                String ref = propertyElement.attributeValue("ref");
                String value = propertyElement.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name, ref, value);
                mutablePropertyValues.addPropertyValue(propertyValue);
            }
            // 4.将MutablePropertyValues对象封装到BeanDefinition对象中
            beanDefinition.setPropertyValues(mutablePropertyValues);

            // 5.将BeanDefinition对象注册到注册表中
            registry.registerBeanDefinition(id, beanDefinition);
        }
    }
}

pom.xml

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

IOC容器相关类

BeanFactory接口

在该接口中定义 IOC 容器的统一规范即获取 bean 对象。

// IOC容器父接口
public interface BeanFactory {
    
    
    
	// 根据bean对象的名称获取bean对象
    Object getBean(String name) throws Exception;

	// 根据bean对象的名称获取bean对象,并进行类型转换
    <T> T getBean(String name, Class<? extends T> clazz) throws Exception;
}

ApplicationContext接口

该接口的所有的子实现类对 bean 对象的创建都是非延时的,也就是说(使用者)在创建容器对象的时候,就会去加载配置文件,并实例化 bean 对象,最终将其存储在容器里面。

所以在该接口中定义 refresh() 方法,该方法主要完成以下两个功能:

  • 加载配置文件。
  • 根据注册表中的 BeanDefinition 对象封装的数据进行 bean 对象的创建。
// 定义非延时加载功能
public interface ApplicationContext extends BeanFactory {
    
    
    
	// 进行配置文件加载并进行对象创建
    void refresh() throws IllegalStateException, Exception;
}

AbstractApplicationContext类

  • 作为 ApplicationContext 接口的子类,所以该类也是非延时加载,所以需要在该类中定义一个 Map 集合,作为 bean 对象存储的容器。
  • 声明 BeanDefinitionReader 类型的变量,用来进行 xml 配置文件的解析,符合单一职责原则。
    • BeanDefinitionReader 类型的对象创建交由子类实现,因为只有子类明确到底创建 BeanDefinitionReader 哪个子实现类对象。
// ApplicationContext接口的子实现类,用于立即加载
public abstract class AbstractApplicationContext implements ApplicationContext {
    
    

    // 声明解析器变量。注意,这里我们只是声明解析器变量而已,具体的对象交由子类去创建。
    protected BeanDefinitionReader beanDefinitionReader;
    // 用来存储bean对象的容器 key存储的是bean的id值,value存储的是bean对象
    protected Map<String, Object> singletonObjects = new HashMap<String, Object>();

    // 存储配置文件的路径
    protected String configLocation;

    public void refresh() throws IllegalStateException, Exception {
    
    
        // 加载BeanDefinition对象。我们只需要去调用解析器里面的方法即可。
        beanDefinitionReader.loadBeanDefinitions(configLocation);
        // 初始化bean(创建bean对象)
        finishBeanInitialization();
    }
  
    /*
     * bean对象的初始化
     * 如果我们要进行bean对象的初始化,很显然,我们需要先获取BeanDefinition对象,
     * 因为BeanDefinition对象里面记录了bean的相关信息,只有拿到这些信息,你才能去创建对象。
     * 而BeanDefinition对象又是被注册在注册表里面的,所以首先我们还得先去获取对应的注册表对象!
     */
    private void finishBeanInitialization() throws Exception {
    
    
        // 获取注册表对象
        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
        // 获取BeanDefinition对象
        String[] beanNames = registry.getBeanDefinitionNames();

        for (String beanName : beanNames) {
    
    
            // 进行bean的初始化
            getBean(beanName);
        }
    }
}

注意:该类 finishBeanInitialization() 方法中调用 getBean() 方法使用到了模板方法模式

ClassPathXmlApplicationContext类

该类主要是加载类路径下的配置文件,并进行 bean 对象的创建,主要完成以下功能:

  • 在构造方法中,创建 BeanDefinitionReader 对象。
  • 在构造方法中,调用 refresh() 方法,用于进行配置文件加载、创建 bean 对象并存储到容器中。
  • 重写父接口中的 getBean() 方法,并实现依赖注入操作(DI)。
/**
 * IOC容器具体的子实现类
 * 用于加载类路径下的xml格式的配置文件
 */
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {
    
    

    public ClassPathXmlApplicationContext(String configLocation) {
    
    
        this.configLocation = configLocation;
        // 构建XmlBeanDefinitionReader对象
        beanDefinitionReader = new XmlBeanDefinitionReader();
        try {
    
    
            this.refresh();
        } catch (Exception e) {
    
    
        }
    }

    // 根据bean的id属性值(名称)获取bean对象
    @Override
    public Object getBean(String name) throws Exception {
    
    

        // 判断对象容器中是否包含指定名称的bean对象,如果包含,直接返回即可,如果不包含,需要自行创建
        Object obj = singletonObjects.get(name);
        if (obj != null) {
    
    
            return obj;
        }

        // 获取BeanDefinition对象
        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
        BeanDefinition beanDefinition = registry.getBeanDefinition(name);
        if (beanDefinition == null) {
    
    
            return null;
        }
        // 获取bean信息中的className(全类名)
        String className = beanDefinition.getClassName();
        // 通过反射创建对象
        Class<?> clazz = Class.forName(className);
        // 这里的beanObj就是UserService对象 只不过现在还是个空壳
        Object beanObj = clazz.newInstance();

        // 进行依赖注入操作
        MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
        for (PropertyValue propertyValue : propertyValues) {
    
    
            // 获取name属性值
            String propertyName = propertyValue.getName();
            // 获取value属性
            String value = propertyValue.getValue();
            // 获取ref属性
            String ref = propertyValue.getRef();
            // 对于value属性和ref属性必然只能存在一个 所以需要进行判断
            // ref一般是一个bean对象,而value只是一个普通的属性值
            if (ref != null && !"".equals(ref)) {
    
    
                // 获取依赖的bean对象
                Object bean = getBean(ref);
                // 拼接方法名
                String methodName = StringUtils.getSetterMethodByFieldName(propertyName);
                // 获取所有的方法对象
                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
    
    
                    if (methodName.equals(method.getName())) {
    
    
                        // 执行该setter方法
                        // 往beanObj中注入bean对象
                        method.invoke(beanObj, bean);
                    }
                }
            }

            if (value != null && !"".equals(value)) {
    
    
                // 拼接方法名
                String methodName = StringUtils.getSetterMethodByFieldName(propertyName);
                // 获取method对象
                Method method = clazz.getMethod(methodName, String.class);
                // 往beanObj中注入value值
                method.invoke(beanObj, value);
            }
        }

        // 在返回beanObj对象之前,将该对象存储到map容器中
        singletonObjects.put(name, beanObj);
        return beanObj;
    }

    @Override
    public <T> T getBean(String name, Class<? extends T> clazz) throws Exception {
    
    
        Object bean = getBean(name);
        if (bean != null) {
    
    
            // 类型强转
            return clazz.cast(bean);
        }
        return null;
    }
}

StringUtils

// String工具类
public class StringUtils {
    
    
    
    private StringUtils() {
    
    
    }

    // userDao ==> setUserDao
    public static String getSetterMethodByFieldName(String fieldName) {
    
    
        String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        return methodName;
    }
}

整体逻辑大概就是:

  • 首先我们有一个 BeanFactory 顶级父接口,定义统一的规范;
  • 然后我们再搞一个 ApplicationContext 接口继承 BeanFactory,目的就是为了实现非延时加载 BD 对象;
  • 然后创建一个 AbstractApplicationContext 子实现类
    • 它主要实现非延加载时的功能,也就是 refresh() 方法,它调用了 XmlBeanDefinitionReader#loadBeanDefinitions 方法,这个方法可以加载并解析 xml 文件,将所有 bean 标签封装为 BD 对象,并注册到注册表中;
      • 随后我们调用 getBean() 方法初始化所有的 bean 对象,这个方法在具体的子类中实现;
    • 具体的 BeanDefinitionReader 类型的对象由子类创建,因为只有子类才知道是什么类型;
  • 创建具体子实现类 ClassPathXmlApplicationContext
    • 在该类的构造方法中创建具体的 XmlBeanDefinitionReader 对象赋值给父类的 BeanDefinitionReader,并调用 refresh() 方法,用于进行配置文件加载、创建 bean 对象并存储到容器中;
    • 重写父接口中的 getBean() 方法,并实现依赖注入操作(DI),**这里就是真正通过反射创建对象的逻辑。**最后将对象存放到容器中。

测试

参考视频

自定义Spring IOC总结

使用到的设计模式

  • 工厂模式。这个使用工厂模式 + 配置文件的方式。
  • 单例模式。Spring IOC 管理的 bean 对象都是单例的,此处的单例不是通过构造器进行单例的控制的,而是 Spring 框架对每一个 bean 只创建了一个对象。
  • 模板方法模式。AbstractApplicationContext 类中的 finishBeanInitialization() 方法调用了子类的 getBean() 方法,因为 getBean() 的实现和环境息息相关。
  • 迭代器模式。对于 MutablePropertyValues 类定义使用到了迭代器模式,因为此类存储并管理 PropertyValue 对象,也属于一个容器,所以给该容器提供一个遍历方式。

Spring 框架其实使用到了很多设计模式,如 AOP 使用到了代理模式,选择 JDK 代理或者 CGLIB 代理使用到了策略模式,还有适配器模式,装饰者模式,观察者模式等。

符合大部分设计原则。

整个设计和 Spring 的设计还是有一定的出入

Spring 框架底层是很复杂的,进行了很深入的封装,并对外提供了很好的扩展性。而我们自定义 Spring IOC 有以下几个目的:

  • 了解 Spring 底层对对象的大体管理机制。
  • 了解设计模式在具体的开发中的使用。
  • 以后学习 Spring 源码,通过该案例的实现,可以降低 Spring 源码学习的入门成本。

猜你喜欢

转载自blog.csdn.net/weixin_53407527/article/details/128645080
今日推荐