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

x33g5p2x  于2022-04-10 转载在 Spring  
字(16.2k)|赞(0)|评价(0)|浏览(310)

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 源码

  1. public interface BeanFactory {
  2. String FACTORY_BEAN_PREFIX = "&";
  3. //根据bean的名称获取IOC容器中的的bean对象
  4. Object getBean(String name) throws BeansException;
  5. //根据bean的名称获取IOC容器中的的bean对象,并指定获取到的bean对象的类型,这样我们使用时就不需要进行类型强转了
  6. <T> T getBean(String name, Class<T> requiredType) throws BeansException;
  7. Object getBean(String name, Object... args) throws BeansException;
  8. <T> T getBean(Class<T> requiredType) throws BeansException;
  9. <T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
  10. <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
  11. <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
  12. //判断容器中是否包含指定名称的bean对象
  13. boolean containsBean(String name);
  14. //根据bean的名称判断是否是单例
  15. boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
  16. boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
  17. boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
  18. boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
  19. @Nullable
  20. Class<?> getType(String name) throws NoSuchBeanDefinitionException;
  21. String[] getAliases(String name);
  22. }

在 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源码

  1. public interface BeanDefinitionReader {
  2. //获取BeanDefinitionRegistry注册器对象
  3. BeanDefinitionRegistry getRegistry();
  4. @Nullable
  5. ResourceLoader getResourceLoader();
  6. @Nullable
  7. ClassLoader getBeanClassLoader();
  8. BeanNameGenerator getBeanNameGenerator();
  9. /*
  10. 下面的loadBeanDefinitions都是加载bean定义,从指定的资源中
  11. */
  12. int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException;
  13. int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException;
  14. int loadBeanDefinitions(String location) throws BeanDefinitionStoreException;
  15. int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException;
  16. }

4.BeanDefinitionRegistry

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

BeanDefinitionRegistry 源码

  1. public interface BeanDefinitionRegistry extends AliasRegistry {
  2. //往注册表中注册bean
  3. void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
  4. throws BeanDefinitionStoreException;
  5. //从注册表中删除指定名称的bean
  6. void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
  7. //获取注册表中指定名称的bean
  8. BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
  9. //判断注册表中是否已经注册了指定名称的bean
  10. boolean containsBeanDefinition(String beanName);
  11. //获取注册表中所有的bean的名称
  12. String[] getBeanDefinitionNames();
  13. int getBeanDefinitionCount();
  14. boolean isBeanNameInUse(String beanName);
  15. }

5. 创建容器

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

自定义 Spring IOC

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

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans>
  3. <bean id="userService" class="com.henrik.service.impl.UserServiceImpl">
  4. <property name="userDao" ref="userDao"></property>
  5. </bean>
  6. <bean id="userDao" class="com.henrik.dao.impl.UserDaoImpl"></bean>
  7. </beans>

1.定义 Bean 相关的 pojo 类

PropertyValue类

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

  1. package com.henrik.framework.beans;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. // 用于封装 Bean 标签下的 property 标签的属性
  6. @Data
  7. @AllArgsConstructor
  8. @NoArgsConstructor
  9. public class PropertyValue {
  10. private String name;
  11. private String value;
  12. private String ref;
  13. }

MutablePropertyValues

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

  1. package com.henrik.framework.beans;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. // 用来存储和管理多个 PropertyValue 对象
  6. // 使用迭代器模式
  7. public class MutablePropertyValues implements Iterable<PropertyValue>{
  8. // 定义 list 集合对象,用于存储 PropertyValue 对象
  9. private final List<PropertyValue> propertyValueList;
  10. public MutablePropertyValues() {
  11. propertyValueList = new ArrayList<PropertyValue>();
  12. }
  13. public MutablePropertyValues(List<PropertyValue> propertyValueList){
  14. if(propertyValueList == null) {
  15. this.propertyValueList = new ArrayList<PropertyValue>();
  16. } else {
  17. this.propertyValueList = propertyValueList;
  18. }
  19. }
  20. // 获取所有的 PropertyValue 对象,返回以数组的形式
  21. public PropertyValue[] getPropertyValues(){
  22. // 将集合转化为数组并返回
  23. return propertyValueList.toArray(new PropertyValue[0]);
  24. }
  25. // 根据 name 属性值获取 PropertyValue 对象
  26. public PropertyValue getPropertyValue(String propertyName){
  27. // 遍历集合对象
  28. for (PropertyValue propertyValue : propertyValueList) {
  29. if (propertyValue.getName().equals(propertyName)){
  30. return propertyValue;
  31. }
  32. }
  33. return null;
  34. }
  35. // 判断集合是否为空
  36. public boolean isEmpty(){
  37. return propertyValueList.isEmpty();
  38. }
  39. // 添加 PropertyValue 对象
  40. // 返回当前对象的目的是实现链式编程
  41. public MutablePropertyValues addPropertyValue(PropertyValue pv){
  42. // 判断集合中存储的 PropertyValue 对象是否和传递进来的重复
  43. for (int i = 0; i < propertyValueList.size(); i++) {
  44. // 获取集合中每一个 PropertyValue 对象
  45. PropertyValue currentPv = propertyValueList.get(i);
  46. if (currentPv.getName().equals(pv.getName())){
  47. propertyValueList.set(i, pv);
  48. return this;
  49. }
  50. }
  51. this.propertyValueList.add(pv);
  52. return this;
  53. }
  54. // 判断是否有指定 name 属性值的对象
  55. public boolean contains(String propertyName){
  56. return getPropertyValue(propertyName) != null;
  57. }
  58. // 获取迭代器对象
  59. @Override
  60. public Iterator<PropertyValue> iterator() {
  61. return propertyValueList.iterator();
  62. }
  63. }

BeanDefinition

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

  1. package com.henrik.framework.beans;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. // 用来封装 Bean 信息的,主要包含 id(即Bean对象的名称)、class(需要交由 spring 管理的类的全类名)及子标签 property 数据
  5. @Data
  6. @AllArgsConstructor
  7. public class BeanDefinition {
  8. private String id;
  9. private String className;
  10. private MutablePropertyValues propertyValues;
  11. public BeanDefinition(){
  12. propertyValues = new MutablePropertyValues();
  13. }
  14. }

2.定义注册表相关类

BeanDefinitionRegistry 接口

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

  • 注册 BeanDefinition 对象到注册表中
  • 从注册表中删除指定名称的 BeanDefinition 对象
  • 根据名称从注册表中获取 BeanDefinition 对象
  • 判断注册表中是否包含指定名称的 BeanDefinition 对象
  • 获取注册表中 BeanDefinition 对象的个数
  • 获取注册表中所有的 BeanDefinition 的名称
  1. package com.henrik.framework.beans.factory.support;
  2. import com.henrik.framework.beans.BeanDefinition;
  3. // 注册表对象
  4. public interface BeanDefinitionRegistry {
  5. //注册BeanDefinition对象到注册表中
  6. void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);
  7. //从注册表中删除指定名称的BeanDefinition对象
  8. void removeBeanDefinition(String beanName) throws Exception;
  9. //根据名称从注册表中获取BeanDefinition对象
  10. BeanDefinition getBeanDefinition(String beanName) throws Exception;
  11. boolean containsBeanDefinition(String beanName);
  12. int getBeanDefinitionCount();
  13. String[] getBeanDefinitionNames();
  14. }

SimpleBeanDefinitionRegistry 类

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

  1. package com.henrik.framework.beans.factory.support;
  2. import com.henrik.framework.beans.BeanDefinition;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. public class SimpleBeanDefinitionRegistry implements BeanDefinitionRegistry{
  6. // 定义一个容器,用来存储 BeanDefinition 对象
  7. private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
  8. @Override
  9. public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
  10. beanDefinitionMap.put(beanName, beanDefinition);
  11. }
  12. @Override
  13. public void removeBeanDefinition(String beanName) throws Exception {
  14. beanDefinitionMap.remove(beanName);
  15. }
  16. @Override
  17. public BeanDefinition getBeanDefinition(String beanName) throws Exception {
  18. return beanDefinitionMap.get(beanName);
  19. }
  20. @Override
  21. public boolean containsBeanDefinition(String beanName) {
  22. return beanDefinitionMap.containsKey(beanName);
  23. }
  24. @Override
  25. public int getBeanDefinitionCount() {
  26. return beanDefinitionMap.size();
  27. }
  28. @Override
  29. public String[] getBeanDefinitionNames() {
  30. return beanDefinitionMap.keySet().toArray(new String[0]);
  31. }
  32. }

3.定义解析器相关类

BeanDefinitionReader 接口

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

  • 获取注册表的功能,让外界可以通过该对象获取注册表对象
  • 加载配置文件,并注册 Bean 数据
  1. package com.henrik.framework.beans.factory.support;
  2. // 用于解析配置文件,定义规范
  3. public interface BeanDefinitionReader {
  4. //获取注册表对象
  5. BeanDefinitionRegistry getRegistry();
  6. //加载配置文件并在注册表中进行注册
  7. void loadBeanDefinitions(String configLocation) throws Exception;
  8. }

XmlBeanDefinitionReader 类

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

  1. package com.henrik.framework.beans.factory.xml;
  2. import com.henrik.framework.beans.BeanDefinition;
  3. import com.henrik.framework.beans.MutablePropertyValues;
  4. import com.henrik.framework.beans.PropertyValue;
  5. import com.henrik.framework.beans.factory.support.BeanDefinitionReader;
  6. import com.henrik.framework.beans.factory.support.BeanDefinitionRegistry;
  7. import com.henrik.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
  8. import org.dom4j.Document;
  9. import org.dom4j.Element;
  10. import org.dom4j.io.SAXReader;
  11. import java.io.InputStream;
  12. import java.util.List;
  13. public class XmlBeanDefinitionReader implements BeanDefinitionReader {
  14. // 声明注册表对象
  15. private BeanDefinitionRegistry registry;
  16. public XmlBeanDefinitionReader(){
  17. registry = new SimpleBeanDefinitionRegistry();
  18. }
  19. @Override
  20. public BeanDefinitionRegistry getRegistry() {
  21. return registry;
  22. }
  23. @Override
  24. public void loadBeanDefinitions(String configLocation) throws Exception {
  25. // 使用 dome4j 进行 xml 配置文件的解析
  26. SAXReader reader = new SAXReader();
  27. // 获取类路径下的配置文件
  28. InputStream is = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
  29. Document document = reader.read(is);
  30. // 根据 Document 对象获取标签对象(Beans)
  31. Element rootElement = document.getRootElement();
  32. // 获取根标签下所有的 Bean 标签对象
  33. List<Element> beanElements = rootElement.elements("bean");
  34. // 遍历集合
  35. for (Element beanElement : beanElements) {
  36. // 获取 id 属性
  37. String id = beanElement.attributeValue("id");
  38. // 获取 class 属性
  39. String className = beanElement.attributeValue("class");
  40. // 封装到 BeanDefinition
  41. BeanDefinition beanDefinition = new BeanDefinition();
  42. beanDefinition.setId(id);
  43. beanDefinition.setClassName(className);
  44. // 创建 mutablePropertyValues 对象
  45. MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
  46. // 获取 property 标签
  47. List<Element> propertyElements = beanElement.elements("property");
  48. for (Element propertyElement : propertyElements) {
  49. String name = propertyElement.attributeValue("name");
  50. String value = propertyElement.attributeValue("value");
  51. String ref = propertyElement.attributeValue("ref");
  52. PropertyValue propertyValue = new PropertyValue(name,value,ref);
  53. mutablePropertyValues.addPropertyValue(propertyValue);
  54. }
  55. // 将 mutablePropertyValues 加入 beanDefinition
  56. beanDefinition.setPropertyValues(mutablePropertyValues);
  57. registry.registerBeanDefinition(id,beanDefinition);
  58. }
  59. }
  60. }

4.IOC 容器相关类

BeanFactory 接口

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

  1. package com.henrik.framework.beans.factory;
  2. // IOC 容器父接口
  3. public interface BeanFactory {
  4. Object getBean(String name) throws Exception;
  5. <T> T getBean(String name, Class<? extends T> clazz) throws Exception;
  6. }

ApplicationContext 接口

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

  • 加载配置文件
  • 根据注册表中的 BeanDefinition 对象封装的数据进行 Bean 对象的创建
  1. package com.henrik.framework.context;
  2. import com.henrik.framework.beans.factory.BeanFactory;
  3. // 定义非延时加载功能
  4. public interface ApplicationContext extends BeanFactory {
  5. //进行配置文件加载并进行对象创建
  6. void refresh() throws IllegalStateException, Exception;
  7. }

AbstractApplicationContext 类

  • 作为 ApplicationContext 接口的子类,所以该类也是非延时加载,所以需要在该类中定义一个 Map 集合,作为 Bean 对象存储的容器
  • 声明 BeanDefinitionReader 类型的变量,用来进行 xml 配置文件的解析,符合单一职责原则
  • BeanDefinitionReader 类型的对象创建交由子类实现,因为只有子类明确到底创建 BeanDefinitionReader 哪儿个子实现类对象
  1. package com.henrik.framework.context.support;
  2. import com.henrik.framework.beans.BeanDefinition;
  3. import com.henrik.framework.beans.factory.support.BeanDefinitionReader;
  4. import com.henrik.framework.beans.factory.support.BeanDefinitionRegistry;
  5. import com.henrik.framework.context.ApplicationContext;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. // ApplicationContext 接口的子实现类,用于立即加载
  9. public abstract class AbstractApplicationContext implements ApplicationContext {
  10. // 声明解析器变量
  11. protected BeanDefinitionReader beanDefinitionReader;
  12. // 定义用于存储 Bean 对象的 map 容器
  13. protected Map<String, Object> singletonObjects = new HashMap<>();
  14. // 声明配置文件路径的变量
  15. protected String configLocation;
  16. @Override
  17. public void refresh() throws IllegalStateException, Exception {
  18. // 加载 BeanDefinition 对象
  19. beanDefinitionReader.loadBeanDefinitions(configLocation);
  20. // 初始化 Bean
  21. finishBeanInitialization();
  22. }
  23. private void finishBeanInitialization() throws Exception {
  24. // 获取注册表对象
  25. BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
  26. // 获取 BeanDefinition 对象
  27. String[] beanNames = registry.getBeanDefinitionNames();
  28. for (String beanName : beanNames) {
  29. BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
  30. getBean(beanName);
  31. }
  32. }
  33. }

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

ClassPathXmlApplicationContext 类

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

  • 在构造方法中,创建 BeanDefinitionReader 对象
  • 在构造方法中,调用 refresh() 方法,用于进行配置文件加载、创建 Bean 对象并存储到容器中
  • 重写父接口中的 getBean() 方法,并实现依赖注入操作
  1. package com.henrik.framework.context.support;
  2. import com.henrik.framework.beans.BeanDefinition;
  3. import com.henrik.framework.beans.MutablePropertyValues;
  4. import com.henrik.framework.beans.PropertyValue;
  5. import com.henrik.framework.beans.factory.support.BeanDefinitionRegistry;
  6. import com.henrik.framework.beans.factory.xml.XmlBeanDefinitionReader;
  7. import com.henrik.framework.utils.StringUtils;
  8. import java.lang.reflect.Method;
  9. // IOC 容器的具体实现子类,用于加载类路径下的 xml 格式的配置文件
  10. public class ClassPathXmlApplicationContext extends AbstractApplicationContext{
  11. public ClassPathXmlApplicationContext(String configLocation){
  12. this.configLocation = configLocation;
  13. // 构建解析器对象
  14. beanDefinitionReader = new XmlBeanDefinitionReader();
  15. try {
  16. this.refresh();
  17. }catch (Exception e){
  18. }
  19. }
  20. // 根据 Bean 对象的名称获取 Bean对象
  21. @Override
  22. public Object getBean(String name) throws Exception {
  23. Object obj = singletonObjects.get(name);
  24. if (obj != null) return obj;
  25. BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
  26. BeanDefinition beanDefinition = registry.getBeanDefinition(name);
  27. String className = beanDefinition.getClassName();
  28. Class<?> clazz = Class.forName(className);
  29. Object beanObj = clazz.newInstance();
  30. MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
  31. for (PropertyValue propertyValue : propertyValues) {
  32. String propertyName = propertyValue.getName();
  33. String value = propertyValue.getValue();
  34. String ref = propertyValue.getRef();
  35. if(ref != null && !"".equals(ref)) {
  36. Object bean = getBean(ref);
  37. String methodName = StringUtils.getSetterMethodNameByFieldName(propertyName);
  38. Method[] methods = clazz.getMethods();
  39. for (Method method : methods) {
  40. if(method.getName().equals(methodName)) {
  41. // 执行该 set 方法
  42. method.invoke(beanObj,bean);
  43. }
  44. }
  45. }
  46. if(value != null && !"".equals(value)) {
  47. String methodName = StringUtils.getSetterMethodNameByFieldName(propertyName);
  48. Method method = clazz.getMethod(methodName, String.class);
  49. method.invoke(beanObj,value);
  50. }
  51. }
  52. singletonObjects.put(name,beanObj);
  53. return null;
  54. }
  55. @Override
  56. public <T> T getBean(String name, Class<? extends T> clazz) throws Exception {
  57. Object bean = getBean(name);
  58. if(bean != null) {
  59. return clazz.cast(bean);
  60. }
  61. return null;
  62. }
  63. }

Test

  1. package com.henrik.controller;
  2. import com.henrik.framework.context.ApplicationContext;
  3. import com.henrik.framework.context.support.ClassPathXmlApplicationContext;
  4. import com.henrik.service.UserService;
  5. public class UserController {
  6. public static void main(String[] args) throws Exception {
  7. //1,创建spring的容器对象
  8. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  9. //BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
  10. //2,从容器对象中获取userService对象
  11. UserService userService = applicationContext.getBean("userService", UserService.class);
  12. //3,调用userService方法进行业务逻辑处理
  13. userService.add();
  14. }
  15. }

相关文章