Spring IOC :相关接口分析、手写简易 Spring IOC

Spring IOC 相关接口分析

1.BeanFactory

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

请添加图片描述
其中,BeanFactory 作为最顶层的一个接口,定义了 IOC 容器的基本功能规范,BeanFactory 有三个重要的子接口:ListableBeanFactory、HierarchicalBeanFactory 和 AutowireCapableBeanFactory,但是从类图中可以发现最终的默认实现类是DefaultListableBeanFactory,它实现了所有的接口

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

  • ListableBeanFactory 接口表示这些Bean可列表化
  • HierarchicalBeanFactory 表示这些Bean 是有继承关系的,也就是每个 Bean 可能有父 Bean
  • AutowireCapableBeanFactory 接口定义 Bean 的自动装配规则

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 容器

2.BeanDefinition

Spring IOC 容器管理我们定义的各种 Bean 对象及其相互关系,而 Bean 对象在 Spring 实现中是以 BeanDefinition 来描述的

3.BeanDefinitionReader

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

BeanDefinitionReader源码

public interface BeanDefinitionReader {
    
    

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

	@Nullable
	ResourceLoader getResourceLoader();

	@Nullable
	ClassLoader getBeanClassLoader();

	BeanNameGenerator getBeanNameGenerator();

	/*
		下面的loadBeanDefinitions都是加载bean定义,从指定的资源中
	*/
	int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException;
	int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException;
	int loadBeanDefinitions(String location) throws BeanDefinitionStoreException;
	int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException;
}

4.BeanDefinitionRegistry

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

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);
}

5. 创建容器

ClassPathXmlApplicationContex t对 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.henrik.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
    <bean id="userDao" class="com.henrik.dao.impl.UserDaoImpl"></bean>
</beans>

1.定义 Bean 相关的 pojo 类

PropertyValue类

用于封装 Bean 的属性,就是封装 Bean 标签的子标签 property 标签数据

package com.henrik.framework.beans;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

// 用于封装 Bean 标签下的 property 标签的属性
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PropertyValue {
    
    

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

}

MutablePropertyValues

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

package com.henrik.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

// 用来存储和管理多个 PropertyValue 对象
// 使用迭代器模式
public class MutablePropertyValues implements Iterable<PropertyValue>{
    
    

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

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

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

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

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

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

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


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



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

BeanDefinition

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

package com.henrik.framework.beans;

import lombok.AllArgsConstructor;
import lombok.Data;

// 用来封装 Bean 信息的,主要包含 id(即Bean对象的名称)、class(需要交由 spring 管理的类的全类名)及子标签 property 数据
@Data
@AllArgsConstructor
public class BeanDefinition {
    
    
    private String id;
    private String className;
    private MutablePropertyValues propertyValues;
    
    public BeanDefinition(){
    
    
        propertyValues = new MutablePropertyValues();
    }
}

2.定义注册表相关类

BeanDefinitionRegistry 接口

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

  • 注册 BeanDefinition 对象到注册表中
  • 从注册表中删除指定名称的 BeanDefinition 对象
  • 根据名称从注册表中获取 BeanDefinition 对象
  • 判断注册表中是否包含指定名称的 BeanDefinition 对象
  • 获取注册表中 BeanDefinition 对象的个数
  • 获取注册表中所有的 BeanDefinition 的名称
package com.henrik.framework.beans.factory.support;

import com.henrik.framework.beans.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集合作为注册表容器

package com.henrik.framework.beans.factory.support;

import com.henrik.framework.beans.BeanDefinition;

import java.util.HashMap;
import java.util.Map;

public class SimpleBeanDefinitionRegistry implements BeanDefinitionRegistry{
    
    
    
    // 定义一个容器,用来存储 BeanDefinition 对象
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
    
    @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]);
    }
}

3.定义解析器相关类

BeanDefinitionReader 接口

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

  • 获取注册表的功能,让外界可以通过该对象获取注册表对象
  • 加载配置文件,并注册 Bean 数据
package com.henrik.framework.beans.factory.support;

// 用于解析配置文件,定义规范
public interface BeanDefinitionReader {
    
    
    //获取注册表对象
    BeanDefinitionRegistry getRegistry();
    //加载配置文件并在注册表中进行注册
    void loadBeanDefinitions(String configLocation) throws Exception;
}

XmlBeanDefinitionReader 类

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

package com.henrik.framework.beans.factory.xml;

import com.henrik.framework.beans.BeanDefinition;
import com.henrik.framework.beans.MutablePropertyValues;
import com.henrik.framework.beans.PropertyValue;
import com.henrik.framework.beans.factory.support.BeanDefinitionReader;
import com.henrik.framework.beans.factory.support.BeanDefinitionRegistry;
import com.henrik.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlBeanDefinitionReader implements BeanDefinitionReader {
    
    

    // 声明注册表对象
    private BeanDefinitionRegistry registry;

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

    @Override
    public BeanDefinitionRegistry getRegistry() {
    
    
        return registry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
    
    
        // 使用 dome4j 进行 xml 配置文件的解析
        SAXReader reader = new SAXReader();
        // 获取类路径下的配置文件
        InputStream is = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
        Document document = reader.read(is);
        // 根据 Document 对象获取标签对象(Beans)
        Element rootElement = document.getRootElement();
        // 获取根标签下所有的 Bean 标签对象
        List<Element> beanElements = rootElement.elements("bean");
        // 遍历集合
        for (Element beanElement : beanElements) {
    
    
            // 获取 id 属性
            String id = beanElement.attributeValue("id");
            // 获取 class 属性
            String className = beanElement.attributeValue("class");
            // 封装到 BeanDefinition
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);
            
            // 创建 mutablePropertyValues 对象
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            
            // 获取 property 标签
            List<Element> propertyElements = beanElement.elements("property");
            for (Element propertyElement : propertyElements) {
    
    
                String name = propertyElement.attributeValue("name");
                String value = propertyElement.attributeValue("value");
                String ref = propertyElement.attributeValue("ref");
                PropertyValue propertyValue = new PropertyValue(name,value,ref);
                mutablePropertyValues.addPropertyValue(propertyValue);
            }

            // 将 mutablePropertyValues 加入 beanDefinition
            beanDefinition.setPropertyValues(mutablePropertyValues);
            
            registry.registerBeanDefinition(id,beanDefinition);
        }
    }
}

4.IOC 容器相关类

BeanFactory 接口

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

package com.henrik.framework.beans.factory;

// IOC 容器父接口
public interface BeanFactory {
    
    
    
    Object getBean(String name) throws Exception;
    
    <T> T getBean(String name, Class<? extends T> clazz) throws Exception;
}

ApplicationContext 接口

该接口的所以的子实现类对bean对象的创建都是非延时的,所以在该接口中定义 refresh() 方法,该方法主要完成以下两个功能:

  • 加载配置文件
  • 根据注册表中的 BeanDefinition 对象封装的数据进行 Bean 对象的创建
package com.henrik.framework.context;

import com.henrik.framework.beans.factory.BeanFactory;

// 定义非延时加载功能
public interface ApplicationContext extends BeanFactory {
    
    
    //进行配置文件加载并进行对象创建
    void refresh() throws IllegalStateException, Exception;
}

AbstractApplicationContext 类

  • 作为 ApplicationContext 接口的子类,所以该类也是非延时加载,所以需要在该类中定义一个 Map 集合,作为 Bean 对象存储的容器

  • 声明 BeanDefinitionReader 类型的变量,用来进行 xml 配置文件的解析,符合单一职责原则

  • BeanDefinitionReader 类型的对象创建交由子类实现,因为只有子类明确到底创建 BeanDefinitionReader 哪儿个子实现类对象

package com.henrik.framework.context.support;

import com.henrik.framework.beans.BeanDefinition;
import com.henrik.framework.beans.factory.support.BeanDefinitionReader;
import com.henrik.framework.beans.factory.support.BeanDefinitionRegistry;
import com.henrik.framework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

// ApplicationContext 接口的子实现类,用于立即加载
public abstract class AbstractApplicationContext implements ApplicationContext {
    
    

    // 声明解析器变量
    protected BeanDefinitionReader beanDefinitionReader;

    // 定义用于存储 Bean 对象的 map 容器
    protected Map<String, Object> singletonObjects = new HashMap<>();

    // 声明配置文件路径的变量
    protected String configLocation;

    @Override
    public void refresh() throws IllegalStateException, Exception {
    
    
        // 加载 BeanDefinition 对象
        beanDefinitionReader.loadBeanDefinitions(configLocation);
        // 初始化 Bean
        finishBeanInitialization();
    }

    private void finishBeanInitialization() throws Exception {
    
    
        // 获取注册表对象
        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();

        // 获取 BeanDefinition 对象
        String[] beanNames = registry.getBeanDefinitionNames();

        for (String beanName : beanNames) {
    
    
            BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
            getBean(beanName);
        }
    }

}

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

ClassPathXmlApplicationContext 类

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

  • 在构造方法中,创建 BeanDefinitionReader 对象
  • 在构造方法中,调用 refresh() 方法,用于进行配置文件加载、创建 Bean 对象并存储到容器中
  • 重写父接口中的 getBean() 方法,并实现依赖注入操作
package com.henrik.framework.context.support;

import com.henrik.framework.beans.BeanDefinition;
import com.henrik.framework.beans.MutablePropertyValues;
import com.henrik.framework.beans.PropertyValue;
import com.henrik.framework.beans.factory.support.BeanDefinitionRegistry;
import com.henrik.framework.beans.factory.xml.XmlBeanDefinitionReader;
import com.henrik.framework.utils.StringUtils;

import java.lang.reflect.Method;

// IOC 容器的具体实现子类,用于加载类路径下的 xml 格式的配置文件
public class ClassPathXmlApplicationContext extends AbstractApplicationContext{
    
    

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

        }
    }

    // 根据 Bean 对象的名称获取 Bean对象
    @Override
    public Object getBean(String name) throws Exception {
    
    
        Object obj = singletonObjects.get(name);
        if (obj != null) return obj;

        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
        BeanDefinition beanDefinition = registry.getBeanDefinition(name);

        String className = beanDefinition.getClassName();
        Class<?> clazz = Class.forName(className);
        Object beanObj = clazz.newInstance();
        MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
        for (PropertyValue propertyValue : propertyValues) {
    
    
            String propertyName = propertyValue.getName();
            String value = propertyValue.getValue();
            String ref = propertyValue.getRef();

            if(ref != null && !"".equals(ref)) {
    
    
                Object bean = getBean(ref);
                String methodName = StringUtils.getSetterMethodNameByFieldName(propertyName);
                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
    
    
                    if(method.getName().equals(methodName)) {
    
    
                        // 执行该 set 方法
                        method.invoke(beanObj,bean);
                    }
                }
            }

            if(value != null && !"".equals(value)) {
    
    
                String methodName = StringUtils.getSetterMethodNameByFieldName(propertyName);
                Method method = clazz.getMethod(methodName, String.class);
                method.invoke(beanObj,value);
            }
        }
        singletonObjects.put(name,beanObj);

        return null;
    }

    @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;
    }
}

Test

package com.henrik.controller;


import com.henrik.framework.context.ApplicationContext;
import com.henrik.framework.context.support.ClassPathXmlApplicationContext;
import com.henrik.service.UserService;



public class UserController {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //1,创建spring的容器对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
        //2,从容器对象中获取userService对象
        UserService userService = applicationContext.getBean("userService", UserService.class);
        //3,调用userService方法进行业务逻辑处理
        userService.add();
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_50216270/article/details/124026758