首页 > 其他分享 >Spring Ioc底层原理代码详细解释

Spring Ioc底层原理代码详细解释

时间:2024-09-27 21:20:19浏览次数:3  
标签:xml String Spring 获取 bean path Ioc public 底层

文章目录

概要

文章是看楠哥的视频做的总结,加上自己一些补充,为了方便以后的复习
视频地址

Spring ioc核心技术
xml解析和反射

根据需求编写XML文件,配置需要创建的bean

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
    private Integer num;
    private String brand;
}

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="car1" class="network.hylnetwork.entity.Car">
        <property name="num" value="1"></property>
        <property name="brand" value="奥迪"></property>
    </bean>
    <bean id="car2" class="network.hylnetwork.entity.Car">
        <property name="num" value="2"></property>
        <property name="brand" value="奥拓"></property>
    </bean>
</beans>

编写程序读取XML文件,获取bean相关信息,类,属性,id

前提知识点Dom4j

DOM4J简介
DOM4J是 dom4j.org 出品的一个开源 XML 解析包。DOM4J应用于 Java 平台,采用了 Java 集合框架并完全支持 DOM,SAX 和 JAXP。

DOM4J 使用起来非常简单。只要你了解基本的 XML-DOM 模型,就能使用。

Dom:把整个文档作为一个对象。

DOM4J 最大的特色是使用大量的接口。

了解更多参考:Dom4j完整教程详解

导入dom4j依赖

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

仿写ClassPathXmlApplicationContext实现ApplicationContext

public class MyClassPathXmlApplicationContext implements ApplicationContext{

}

实现ApplicationContext的方法
在这里插入图片描述
测试能否获取xml文件,在MyClassPathXmlApplicationContext添加无参构造和parseXMl方法

 public MyClassPathXmlApplicationContext(String path){
        parseXML(path);
    }
    public void  parseXML(String path){
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read("src/main/resources/"+path);//看提示
            System.out.println(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

测试类

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new MyClassPathXmlApplicationContext("spring-ioc.xml");
    }
}

成功获取xml文件,也就是我们获取到了spring-ioc.xml文件,如下运行结果在这里插入图片描述提示因为路径不完整,需要手动拼接不完整部分项目路径,否则就会出现如下错误)可以看到缺少了“src/main/resources/”部分,所以我们手动拼接上

org.dom4j.DocumentException: G:\AllSpace\IdeaSpace\Spring\spring-ioc.xml (系统找不到指定的文件。) Nested exception: G:\AllSpace\IdeaSpace\Spring\spring-ioc.xml (系统找不到指定的文件。

获取根节点,也就是我们xml文件中的beans

 public void  parseXML(String path){
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read("src/main/resources/"+path);//看提示
            Element rootElement = document.getRootElement();
            System.out.println(rootElement);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

运行结果如下
在这里插入图片描述

xml解析就像剥洋葱一样,是一层一层往下走的
获取根节点的迭代器,其实也就是为了得到beans中的bean

 public void  parseXML(String path){
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read("src/main/resources/"+path);//看提示
            Element rootElement = document.getRootElement();
            Iterator<Element> rootIter = rootElement.elementIterator();//根节点迭代器
            while (rootIter.hasNext()){
                Element bean = rootIter.next();//获取bean
                System.out.println(bean);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

运行结果如下
将beans中的两个bean都获取到了在这里插入图片描述在这里插入图片描述
获取到bean之后就是获取bean的类、属性、id信息

  public void  parseXML(String path){
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read("src/main/resources/"+path);//看提示
            Element rootElement = document.getRootElement();
            Iterator<Element> rootIter = rootElement.elementIterator();//根节点迭代器
            while (rootIter.hasNext()){
                Element bean = rootIter.next();//获取bean
                String idstr = bean.attributeValue("id");  //获取bean中的id
                String className = bean.attributeValue("class");  //获取bean中的class
                System.out.println(idstr);
                System.out.println(className);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

结果如下
在这里插入图片描述
可以看到和xml配置文件中的信息相匹配
在这里插入图片描述
获取属性 也就是bean中的property

  给属性赋值
                Iterator<Element> beanIter = bean.elementIterator();
                while (beanIter.hasNext()){
                    Element property = beanIter.next();
                    System.out.println(property);
                }

结果如下
在这里插入图片描述
对应了四个property
在这里插入图片描述

根据第二步获取到的信息,结合反射机制动态创建对象,同时完成属性赋值

//              反射动态创建对象
                Class clazz = Class.forName(className);
                Constructor constructor = clazz.getConstructor();

将创建好的bean存入到Map集合,设置key-value映射

  private Map<String,Object> iocMap; //创建map集合

    public MyClassPathXmlApplicationContext(String path){
        iocMap = new HashMap<>(); 
        parseXML(path);
    }
    public void  parseXML(String path){
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read("src/main/resources/"+path);//看提示
            Element rootElement = document.getRootElement();
            Iterator<Element> rootIter = rootElement.elementIterator();//根节点迭代器
            while (rootIter.hasNext()){
                Element bean = rootIter.next();//获取bean
                String idstr = bean.attributeValue("id");  //获取bean中的id
                String className = bean.attributeValue("class");  //获取bean中的class
//              反射动态创建对象
                Class clazz = Class.forName(className);
                Constructor constructor = clazz.getConstructor();
                Object object = constructor.newInstance();
                iocMap.put(idstr,object); //将bean存入map集合中,设置key-value映射
            }
        } catch (DocumentException | ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

提供方法从Map中通过id获取到对象的value

修改getBean方法

  @Override
    public Object getBean(String s) throws BeansException {
        return iocMap.get(s);
    }

测试类

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new MyClassPathXmlApplicationContext("spring-ioc.xml");
        Object car1 = applicationContext.getBean("car1");
        System.out.println(car1);
    }
}

运行结果如下
在这里插入图片描述

标签:xml,String,Spring,获取,bean,path,Ioc,public,底层
From: https://blog.csdn.net/weixin_54028135/article/details/132025773

相关文章

  • SpringBoot整合JPA实现CRUD详解
    SpringBoot版本是2.0以上(2.6.13)JDK是1.8一、依赖<dependencies><!--jdbc--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artif......
  • springboot+vue柚趣商城【开题+程序+论文】
    系统程序文件列表开题报告内容研究背景随着互联网技术的飞速发展,电子商务已成为推动全球经济增长的重要力量。特别是在“新零售”与“社交电商”兴起的背景下,消费者对购物体验的要求日益提升,不仅追求商品的多样性与品质,更渴望在购物过程中获得乐趣与社交互动。柚趣商城应运......
  • springboot+vue幼儿园管理系统【开题+程序+论文】
    系统程序文件列表开题报告内容研究背景随着社会对学前教育重视程度的不断提升,幼儿园作为儿童早期教育的重要场所,其管理水平直接影响着教育质量与幼儿的发展。当前,许多幼儿园仍采用传统的人工管理方式,不仅效率低下,还容易出现信息遗漏、统计错误等问题。在信息化时代背景下,构......
  • springboot+vue幼儿学前教育系统【开题+程序+论文】
    系统程序文件列表开题报告内容研究背景:随着社会对幼儿教育重视程度的日益提升,构建一个高效、全面、安全的幼儿学前教育系统显得尤为重要。当前,传统幼儿教育管理模式面临着信息孤岛、家校沟通不畅、教育资源分配不均等问题,难以满足现代家庭对高质量学前教育的需求。特别是在......
  • 基于Java+Springboot+Vue开发的健身房管理系统源码+参考文章1.3万字
    项目简介该项目是基于Java+Springboot+Vue开发的健身房管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的健身房管理系统项目,大学生可以在实践中学习和提升......
  • 基于Java+Springboot+Vue开发的家具管理系统源码+开发文档
    项目简介该项目是基于Java+Springboot+Vue开发的家具管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的家具管理系统项目,大学生可以在实践中学习和提升自己......
  • 基于Java+Springboot+Vue开发的网上商城管理系统源码+文章
    项目简介该项目是基于Java+Springboot+Vue开发的网上商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的网上商城管理系统项目,大学生可以在实践中学习和......
  • 基于Java+Springboot+Vue开发的医院门诊预约挂号系统源码+参考文章1.2万字
    项目简介该项目是基于Java+Springboot+Vue开发的医院门诊预约挂号系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的门诊预约挂号管理系统项目,大学生可以在实践......
  • springboot+vue游泳馆管理系统【开题+程序+论文】
    系统程序文件列表开题报告内容研究背景随着人们生活水平的提高和健康意识的增强,游泳作为一项全身性的运动,日益受到广大市民的青睐。游泳馆作为提供游泳服务的公共场所,其运营管理和服务质量直接影响到用户体验及健身效果。然而,传统的人工管理模式存在效率低下、信息滞后、容......
  • springboot+vue游戏资讯网站【开题+程序+论文】
    系统程序文件列表开题报告内容研究背景随着互联网的飞速发展,电子游戏已成为全球范围内广泛流行的一种娱乐方式,其影响力渗透到了文化、社交、经济等多个领域。在这个背景下,游戏资讯的获取与传播变得尤为重要。玩家群体对于新游戏的发布、游戏攻略、赛事活动及行业动态等信息......