3 定义解析器相关类

3.1 BeanDefinitionReader接口

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

  • 获取注册表的功能,让外界可以通过该对象获取注册表对象。

  • 加载配置文件,并注册bean数据。

/**
* @version v1.0
* @ClassName: BeanDefinitionReader
* @Description:
*     用来解析配置文件的,而该接口只是定义了规范
*/
public interface BeanDefinitionReader {

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

3.2 XmlBeanDefinitionReader类

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

/**
* @version v1.0
* @ClassName: XmlBeanDefinitionReader
* @Description: 针对xml配置文件进行解析的类
*/
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

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

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

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

   public void loadBeanDefinitions(String configLocation) throws Exception {
       //使用dom4j进行xml配置文件的解析   须需在pom文件里面引入dom4j 1.6.1版本
       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");

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

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

           //获取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);
          }
           //将mutablePropertyValues对象封装到BeanDefinition对象中
           beanDefinition.setPropertyValues(mutablePropertyValues);

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

4 IOC容器相关类

4.1 BeanFactory接口

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

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

4.2 ApplicationContext接口

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

  • 加载配置文件。

  • 根据注册表中的BeanDefinition对象封装的数据进行bean对象的创建。

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

4.3 AbstractApplicationContext类

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

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

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

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

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

       //获取BeanDefinition对象
       String[] beanNames = registry.getBeanDefinitionNames();
       for (String beanName : beanNames) {
           //进行bean的初始化
           getBean(beanName);
      }
  }
}

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

4.4 ClassPathXmlApplicationContext类

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

  • 在构造方法中,创建BeanDefinitionReader对象。

  • 在构造方法中,调用refresh()方法,用于进行配置文件加载、创建bean对象并存储到容器中。

  • 重写父接口中的getBean()方法,并实现依赖注入操作。

/**
* @version v1.0
* @ClassName: ClassPathXmlApplicationContext
* @Description: 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对象
   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);
       //获取bean信息中的className
       String className = beanDefinition.getClassName();
       //通过反射创建对象
       Class<?> clazz = Class.forName(className);
       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();
           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方法
                       method.invoke(beanObj,bean);
                  }
              }
          }

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

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

   public <T> T getBean(String name, Class<? extends T> clazz) throws Exception {
       Object bean = getBean(name);
       if(bean == null) {
           return null;
      }
       return clazz.cast(bean);
  }
}


/**
* @version v1.0
* @ClassName: StringUtils
*/
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;
  }
}

如此已经完成,只需对这个工程执行mvn install打包成一个jar,通过pom文件引入到其他工程(例如:spring使用回顾)中即可进行测试。

// 这是另外一个工程
// 引用的类均来自于前面自定义的类
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();
  }

设计模式(三十一)----综合应用-自定义Spring框架-自定义Spring IOC-定义解析器、IOC容器相关类的更多相关文章

  1. 《经久不衰的Spring框架:Spring+SpringMVC+MyBatis 整合》

    前言 主角即Spring.SpringMVC.MyBatis,即所谓的SSM框架,大家应该也都有所了解,概念性的东西就不写了,有万能的百度.之前没有记录SSM整合的过程,这次刚刚好基于自己的一个小项目 ...

  2. 什么是Spring框架? Spring框架有哪些主要的模块?

    Spring框架是一个为java应用程序的开发提供了综合,广泛的基础性支持的java平台.Spring帮助开发者解决了开发中基础性的问题,使得开发人员可以专注于应用程序的开发.Spring框架本身亦是 ...

  3. Spring框架(1)---Spring入门

    Spring入门 为了能更好的理解先讲一些有的没的的东西: 什么是Spring Spring是分层的JavaSE/EE full-stack(一站式) 轻量级开源框架 分层 SUN提供的EE的三层结构 ...

  4. 【spring框架】spring获取webapplicationcontext,applicationcontext几种方法详解--(转)

    方法一:在初始化时保存ApplicationContext对象代码:ApplicationContext ac = new FileSystemXmlApplicationContext(" ...

  5. Spring框架学习-Spring和IOC概述

    一:什么是Spring框架? spring是一个分层的javase/EEfull-stack(一站式)轻量级的java开源框架.是为了解决企业开发的复杂性而创建的.框架的主要优势是分层架构,Sprin ...

  6. Spring框架:Spring安全

    在传统的Web发展,安全码被分散在各个模块,这样方便管理,有时你可能会错过一个地方导致安全漏洞.为了解决这个问题,它的发明Spring Security.它是业务逻辑的有关安全代码的作用全部转移到一个 ...

  7. 什么是spring框架?spring特点与好处,使用spring框架的好处是什么?

    转载:https://blog.csdn.net/hht006158/article/details/80181207. Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Ja ...

  8. 一句话概括下spring框架及spring cloud框架主要组件

    作为java的屌丝,基本上跟上spring屌丝的步伐,也就跟上了主流技术.spring 顶级项目:Spring IO platform:用于系统部署,是可集成的,构建现代化应用的版本平台,具体来说当你 ...

  9. Spring(二):Spring框架&Hello Spring

    Spring是一个开源框架,是为了解决企业应用程序开发复杂性而创建的.框架的主要优势之一就是其分层架构,分层架构允许您选择使用哪一个组件,同时为J2EE应用程序开发提供集成的框架. Spring 框架 ...

  10. Spring框架学习——Spring的体系结构详解

    1.Spring简介 Spring是一个轻量级Java开发框架,最早有Rod Johnson创建,目的是为了解决企业级应用开发的业务逻辑层和其他各层的耦合问题.它是一个分层的JavaSE/JavaEE ...

随机推荐

  1. vue组件 子组件没有事件怎么 向父组件传递数据

    通过ref去接收值!!! 需求图片 代码实现 //----------父组件 <div class="fingerprint-bottom"> <el-tabs ...

  2. UVA10404

    由题意可知,这题和巴什博弈没什么关系了 相似题目:AtCoder Beginner Contest 278 F - Shiritori 预备知识:DP,博弈论的必胜态和必败态 问题的关键是确定\(f_ ...

  3. Centos7下搭建部署DoClever接口管理平台

    项目地址: github:https://github.com/sx1989827/DOClever 码云:https://gitee.com/sx1989827/SBDoc 1.根据官方文档,先安装 ...

  4. python 编程找出矩阵中的幸运数字:说明,在一个给定的M*N的矩阵(矩阵中的取值0-1024,且各不相同),如果某一个元素的值在同一行中最小,并且在同一列中元素最大,那么该数字为幸运数字。

    假设给定矩阵如下: matrix=[[10,36,52], [33,24,88], [66,76,99]] 那么输出结果应为66(同时满足条件) 代码如下: arr=[[10,36,52], [33, ...

  5. (五).JavaScript的函数

    1. 函数 1.1 函数基础简介 函数介绍 函数:具有特定功能的代码块 本质:一种对象数据类型 功能:1. 代码复用 2. 项目模块化 函数组成(两者必须同时存在): 1. 函数定义 2. 函数调用 ...

  6. 使用selemium被反爬解决方法

    使用selenium进行自动化的时候,如csdn登录时可能会遇到检测反爬,从而需要验证       1. 反爬 有时候,我们利用 Selenium 自动化爬取某些网站时,极有可能会遭遇反爬. 实际上, ...

  7. Word 找不到 Endnote选项

    Word 2010 找不到 Endnote选项汇总(不是Office有效加载项)因为基本百度上的问题我全都遇到了-说明:在我们使用Word的过程中,常常发现没有Endnote选项.然后去找百度方法:1 ...

  8. PostgreSQL 数组类型使用详解

    PostgreSQL 数组类型使用详解 PostgreSQL 数组类型使用详解 可能大家对 PostgreSQL 这个关系型数据库不太熟悉,因为大部分人最熟悉的,公司用的最多的是 MySQL 我们先对 ...

  9. Spring源码构建踩坑记录

    1:Kotlin: warnings found and -Werror specified Kotlin将程序中的警告变更为错误导致的问题,只需要改变一下级别即可,注意看是那个模块的 解决方式:fi ...

  10. Spring--AOP通知类型

    AOP通知类型 前置通知 通知类中的数据在原始数据的前面 后置通知 通知类中的数据在原始数据的后面 环绕通知 若是只是加一个注解: 我们需要这样做:加一个参数: 若是面对有返回值的方法,又有一点不同之 ...