Spring框架体系及Spring IOC思想
目录
- Spring简介
- Spring体系结构
- SpringIOC
- 控制反转思想
- 自定义对象容器
- Spring实现IOC
- Spring容器类型
- 容器接口
- 容器实现类
- 对象的创建方式
- 使用构造方法
- 使用工厂类的方法
- 使用工厂类的静态方法
- 对象的创建策略
- 对象的销毁时机
- 生命周期方法
- 获取Bean对象的方式
- 通过id/name获取
- 通过类型获取
- 通过类型+id/name获取
Spring简介

Spring是一个开源框架,为简化企业级开发而生。它以IOC(控制反转)和AOP(面向切面)为思想内核,提供了控制层SpringMVC、数据层SpringData、服务层事务管理等众多技术,并可以整合众多第三方框架。
Spring将很多复杂的代码变得优雅简洁,有效的降低代码的耦合度,极大的方便项目的后期维护、升级和扩展。
Spring官网地址:https://spring.io/
Spring体系结构

Spring框架根据不同的功能被划分成了多个模块,这些模块可以满足一切企业级应用开发的需求,在开发过程中可以根据需求有选择性地使用所需要的模块。
- Core Container:Spring核心模块,任何功能的使用都离不开该模块,是其他模块建立的基础。
- Data Access/Integration:该模块提供了数据持久化的相应功能。
- Web:该模块提供了web开发的相应功能。
- AOP:提供了面向切面编程实现
- Aspects:提供与AspectJ框架的集成,该框架是一个面向切面编程框架。
- Instrumentation:提供了类工具的支持和类加载器的实现,可以在特定的应用服务器中使用。
- Messaging:为Spring框架集成一些基础的报文传送应用
- Test:提供与测试框架的集成
SpringIOC

控制反转思想
IOC(Inversion of Control) :程序将创建对象的权利交给框架。
之前在开发过程中,对象实例的创建是由调用者管理的,代码如下:
public interface StudentDao {// 根据id查询学生Student findById(int id);
}public class StudentDaoImpl implements StudentDao{@Overridepublic Student findById(int id) {// 模拟从数据库查找出学生return new Student(1,"张三","北京");}
}public class StudentService {public Student findStudentById(int id){// 此处就是调用者在创建对象StudentDao studentDao = new StudentDaoImpl();return studentDao.findById(1);}
}
这种写法有两个缺点:
- 浪费资源:StudentService调用方法时即会创建一个对象,如果不断调用方法则会创建大量StudentDao对象。
- 代码耦合度高:假设随着开发,我们创建了StudentDao另一个更加完善的实现类StudentDaoImpl2,如果在StudentService中想使用StudentDaoImpl2,则必须修改源码。
而IOC思想是将==创建对象的权利交给框架==,框架会帮助我们创建对象,分配对象的使用,控制权由程序代码转移到了框架中,控制权发生了反转,这就是Spring的IOC思想。而IOC思想可以完美的解决以上两个问题。
自定义对象容器
接下来我们通过一段代码模拟IOC思想。创建一个集合容器,先将对象创建出来放到容器中,需要使用对象时,只需要从容器中获取对象即可,而不需要重新创建,此时容器就是对象的管理者。
创建实体类
public class Student {private int id;private String name;private String address;// 省略getter/setter/构造方法/tostring }创建Dao接口和实现类
public interface StudentDao {// 根据id查询学生Student findById(int id); }public class StudentDaoImpl implements StudentDao{@Overridepublic Student findById(int id) {// 模拟从数据库查找出学生return new Student(1,"张三","北京");} }public class StudentDaoImpl2 implements StudentDao{@Overridepublic Student findById(int id) {// 模拟根据id查询学生System.out.println("新方法!!!");return new Student(1,"张三","北京");} }创建配置文件bean.properties,该文件中定义管理的对象
studentDao=com.Spring.dao.StudentDaoImpl创建容器管理类,该类在类加载时读取配置文件,将配置文件中配置的对象全部创建并放入容器中。
public class Container {static Map<String,Object> map = new HashMap();static {// 读取配置文件InputStream is = Container.class.getClassLoader().getResourceAsStream("bean.properties");Properties properties = new Properties();try {properties.load(is);} catch (IOException e) {e.printStackTrace();}// 遍历配置文件的所有配置Enumeration<Object> keys = properties.keys();while (keys.hasMoreElements()){String key = keys.nextElement().toString();String value = properties.getProperty(key);try {// 创建对象Object o = Class.forName(value).newInstance();// 将对象放入集合中map.put(key,o);} catch (Exception e) {e.printStackTrace();}}}// 从容器中获取对象public static Object getBean(String key){return map.get(key);} }创建Dao对象的调用者StudentService
public class StudentService {public Student findStudentById(int id){// 从容器中获取对象StudentDao studentDao = (StudentDao) Container.getBean("studentDao");System.out.println(studentDao.hashCode());return studentDao.findById(id);} }测试StudentService
public class Test {public static void main(String[] args) {StudentService studentService = new StudentService();System.out.println(studentService.findStudentById(1));System.out.println(studentService.findStudentById(1));} }
测试结果:
StudentService从容器中每次拿到的都是同一个StudentDao对象,节约了资源。
如果想使用StudentDaoImpl2对象,只需要修改bean.properties的内容为
studentDao=com.Spring.dao.StudentDaoImpl2即可,无需修改Java源码。
Spring实现IOC
接下来我们使用Spring实现IOC,Spring内部也有一个容器用来管理对象。
创建Maven工程,引入依赖
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.13</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency> </dependencies>创建POJO类、Dao类和接口
public class Student {private int id;private String name;private String address;// 省略getter/setter/构造方法/tostring }public interface StudentDao {// 根据id查询学生Student findById(int id); }public class StudentDaoImpl implements StudentDao{@Overridepublic Student findById(int id) {// 模拟从数据库查找出学生return new Student(1,"张三","北京");} }编写xml配置文件,配置文件中配置需要Spring帮我们创建的对象。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="studentDao" class="com.Spring.dao.StudentDaoImpl"></bean></beans>测试从Spring容器中获取对象。
public class TestContainer {@Testpublic void t1(){// 创建Spring容器ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");// 从容器获取对象StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao");StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao");System.out.println(studentDao1.hashCode());System.out.println(studentDao2.hashCode());System.out.println(studentDao1.findById(1));} }
Spring容器类型
容器接口
BeanFactory:BeanFactory是Spring容器中的顶层接口,它可以对Bean对象进行管理。
ApplicationContext:ApplicationContext是BeanFactory的子接口。它除了继承 BeanFactory的所有功能外,还添加了对国际化、资源访问、事件传播等方面的良好支持。
ApplicationContext有以下三个常用实现类:
容器实现类
ClassPathXmlApplicationContext:该类可以从项目中读取配置文件FileSystemXmlApplicationContext:该类从磁盘中读取配置文件AnnotationConfigApplicationContext:使用该类不读取配置文件,而是会读取注解
@Test
public void t2(){// 创建spring容器// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\a\\IdeaProjects\\spring_demo\\src\\main\\resources\\bean.xml");// 从容器中获取对象StudentDao userDao = (StudentDao) ac.getBean("studentDao");System.out.println(userDao);System.out.println(userDao.findById(1));
}
对象的创建方式
Spring会帮助我们创建bean,那么它底层是调用什么方法进行创建的呢?
使用构造方法
Spring默认使用类的空参构造方法创建bean:
// 假如类没有空参构造方法,将无法完成bean的创建
public class StudentDaoImpl implements StudentDao{public StudentDaoImpl(int a){}@Overridepublic Student findById(int id) {// 模拟根据id查询学生return new Student(1,"张三","北京");}
}
使用工厂类的方法
Spring可以调用工厂类的方法创建bean:
创建工厂类,工厂类提供创建对象的方法:
public class StudentDaoFactory {public StudentDao getStudentDao(){return new StudentDaoImpl(1);} }在配置文件中配置创建bean的方式为工厂方式。
<!-- id:工厂对象的id,class:工厂类 --> <bean id="studentDaoFactory" class="com.Spring.dao.StudentDaoFactory"></bean> <!-- id:bean对象的id,factory-bean:工厂对象的id,factory-method:工厂方法 --> <bean id="studentDao" factory-bean="studentDaoFactory" factory-method="getStudentDao"></bean>测试
使用工厂类的静态方法
Spring可以调用工厂类的静态方法创建bean:
创建工厂类,工厂提供创建对象的静态方法。
public class StudentDaoFactory2 {public static StudentDao getStudentDao2() {return new StudentDaoImpl();} }在配置文件中配置创建bean的方式为工厂静态方法。
<!-- id:bean的id class:工厂全类名 factory-method:工厂静态方法 --> <bean id="studentDao" class="com.Spring.dao.StudentDaoFactory2" factory-method="getStudentDao2"></bean>测试
对象的创建策略
Spring通过配置<bean>中的scope属性设置对象的创建策略,共有五种创建策略:
singleton:单例,默认策略。整个项目只会创建一个对象,通过
<bean>中的lazy-init属性可以设置单例对象的创建时机:lazy-init="false"(默认):立即创建,在容器启动时会创建配置文件中的所有Bean对象。
lazy-init="true":延迟创建,第一次使用Bean对象时才会创建。
配置单例策略:
<!-- <bean id="studentDao" class="com.Spring.dao.StudentDaoImpl2" scope="singleton" lazy-init="true"></bean>--> <bean id="studentDao" class="com.Spring.dao.StudentDaoImpl2" scope="singleton" lazy-init="false"> </bean>测试单例策略:
// 为Bean对象的类添加构造方法 public StudentDaoImpl2(){System.out.println("创建StudentDao!!!"); } @Test public void t2(){// 创建Spring容器ApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");// 从容器获取对象StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao");StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao");StudentDao studentDao3 = (StudentDao) ac.getBean("studentDao");System.out.println(studentDao1.hashCode());System.out.println(studentDao2.hashCode());System.out.println(studentDao3.hashCode()); }prototype:多例,每次从容器中获取时都会创建对象。
<!-- 配置多例策略 --> <bean id="studentDao" class="com.Spring.dao.StudentDaoImpl2" scope="prototype"></bean>request:每次请求创建一个对象,只在web环境有效。
session:每次会话创建一个对象,只在web环境有效。
gloabal-session:一次集群环境的会话创建一个对象,只在web环境有效。
对象的销毁时机
对象的创建策略不同,销毁时机也不同:
- singleton:对象随着容器的销毁而销毁。
- prototype:使用JAVA垃圾回收机制销毁对象。
- request:当处理请求结束,bean实例将被销毁。
- session:当HTTP Session最终被废弃的时候,bean也会被销毁掉。
- gloabal-session:集群环境下的session销毁,bean实例也将被销毁。
生命周期方法
Bean对象的生命周期包含创建——使用——销毁,Spring可以配置Bean对象在创建和销毁时自动执行的方法:
定义生命周期方法
public class StudentDaoImpl2 implements StudentDao{// 创建时自动执行的方法public void init(){System.out.println("创建StudentDao!!!");}// 销毁时自动执行的方法public void destory(){System.out.println("销毁StudentDao!!!");} }配置生命周期方法
<!-- init-method:创建对象时执行的方法 destroy-method:销毁对象时执行的方法 --> <bean id="studentDao" class="com.Spring.dao.StudentDaoImpl2" scope="singleton"init-method="init" destroy-method="destory"></bean>测试
@Test public void t3(){// 创建Spring容器ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");// 销毁Spring容器,ClassPathXmlApplicationContext才有销毁容器的方法ac.close(); }
获取Bean对象的方式
Spring有多种获取容器中对象的方式:
通过id/name获取
配置文件
<bean name="studentDao" class="com.Spring.dao.StudentDaoImpl2"></bean>|| <bean id="studentDao" class="com.Spring.dao.StudentDaoImpl2"></bean>获取对象
StudentDao studentDao = (StudentDao) ac.getBean("studentDao");
通过类型获取
配置文件
<bean name="studentDao" class="com.Spring.dao.StudentDaoImpl2"></bean>获取对象
StudentDao studentDao2 = ac.getBean(StudentDao.class);可以看到使用类型获取不需要强转。
通过类型+id/name获取
虽然使用类型获取==不需要强转==,但如果在容器中有一个接口的多个实现类对象,则获取时会报错,此时需要使用类型+id/name获取
配置文件
<bean name="studentDao" class="com.Spring.dao.StudentDaoImpl2"></bean> <bean name="studentDao1" class="com.Spring.dao.StudentDaoImpl"></bean>获取对象
StudentDao studentDao2 = ac.getBean("studentDao",StudentDao.class);
相关文章:
Spring框架体系及Spring IOC思想
目录 Spring简介Spring体系结构SpringIOC控制反转思想自定义对象容器Spring实现IOCSpring容器类型容器接口容器实现类对象的创建方式使用构造方法使用工厂类的方法使用工厂类的静态方法对象的创建策略对象的销毁时机生命周期方法获取Bean对象的方式通过id/name获取通过类型获取…...
WT588F02B-8S语音芯片:16位DSP技术引领个性化功能产品新时代
随着科技的快速发展,语音芯片作为人机交互的核心组件,在各个领域的应用越来越广泛。唯创知音推出的WT588F02B-8S语音芯片,以其强大的16位DSP技术和丰富的内置资源,正成为行业内的翘楚。 首先,唯创知音WT588F02B-8S是一…...
数字逻辑电路基础-时序逻辑电路之移位寄存器
文章目录 一、移位寄存器定义二、verilog源码三、仿真结果 一、移位寄存器定义 移位寄存器定义 A shift register is a type of digital circuit using a cascade of flip flops where the output of one flip-flop is connected to the input of the next. 移位寄存器是一种将…...
DEM分析
一、实验名称: DEM分析 二、实验目的: 通过本实验练习,掌握DEM的建立与应用基本方法。 三、实验内容和要求: 实验内容: 利用ARCGIS软件相关分析工具及实验数据,创建DEM,并计算相应坡度的区…...
全面探讨HTTP协议从0.9到3.0版本的发展和特点
前言: 最近的几场面试都问到了http的相关知识点,博主在此结合书籍和网上资料做下总结。本篇文章讲收录到秋招专题,该专栏比较适合刚入坑Java的小白以及准备秋招的大佬阅读。 如果文章有什么需要改进的地方欢迎大佬提出,对大佬有帮…...
中通快递查询入口,根据物流更新量筛选出需要的单号记录
批量中通快递单号的物流信息,根据物流更新量将需要的单号记录筛选出来。 所需工具: 一个【快递批量查询高手】软件 中通快递单号若干 操作步骤: 步骤1:运行【快递批量查询高手】软件,并登录 步骤2:点击主…...
Arraylist案例
Arraylist是使用最频繁的一个集合,它与数组类似,不同之处在于它可以动态改变长度,不够了可以扩容。 案例: 我的思考: 首先多个菜品信息可以用Arraylist 来存储,那我们需要再创建一个菜品类Food࿰…...
『heqingchun-Ubuntu系统+x86架构+配置编译安装使用yolov5-6.0+带有TensorRT硬件加速+C++部署』
Ubuntu系统x86架构配置编译安装使用yolov5-6.0带有TensorRT硬件加速C部署 一、准备文件 1.yolov5-6.0.zip 官网下载 网址: https://github.com/ultralytics/yolov5/tree/v6.0操作: 点击"Code"下的"Download ZIP" 下载得到yolov5…...
优秀的员工成为公司的管理者之后,为何表现平庸?因为他们缺乏这些思维
在企业的实践中,我们发现平时能力最强的员工,在被提拔到管理层之后就慢慢变得平庸了,再也不是以前那个无所不能的“企业能人”了,甚至在一些事情的处理上还会有些笨拙。面对这种情况,我们一定会感觉很疑惑,…...
MySQL简单介绍
简单了解MySQL MySQL语句分类 SQL语句分类 DDL:数据定义语句 create表,库.….] DML:数据操作语句 [增加insert,修改 update,删除delete] DQL:数据查询语句 [select] DCL:数据控制语句 …...
【开源】基于JAVA的天然气工程业务管理系统
项目编号: S 021 ,文末获取源码。 \color{red}{项目编号:S021,文末获取源码。} 项目编号:S021,文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块三、使用角色3.1 施工人员3.2 管理员 四…...
虚幻学习笔记—点击场景3D物体的两种处理方式
一、前言 本文使用的虚幻引擎为5.3.2,两种方式分别为:点击根物体和精准点击目标物体。 二、实现 2.1、玩家控制器中勾选鼠标点击事件:这一步很重要,如图2.1.1所示:在自定义玩家控制器中勾 图2.1.1 选该项,…...
AIGC|LangChain新手入门指南,5分钟速读版!
如果你用大语言模型来构建AI应用,那你一定不可能绕过LangChain,LangChain是现在最热门的AI应用框架之一,去年年底才刚刚发布,它在github上已经有了4.6万颗星的点赞了,在github社区上,每天都有众多大佬,用它…...
探索 Linux vim/vi 编辑器:介绍、模式以及基本操作演示
💐作者:insist-- 💐个人主页:insist-- 的个人主页 理想主义的花,最终会盛开在浪漫主义的土壤里,我们的热情永远不会熄灭,在现实平凡中,我们终将上岸,阳光万里 ❤️欢迎点…...
Centos 7 在线安装(RPM) PostgreSQL 14 15 16
目录 一、官网下载地址二、检查系统是否安装其他版本PostgreSQL数据库三、安装数据库四、配置数据库(默认方式一)4.1初始化用户密码4.2修改postgresql.conf文件4.3修改pg_hba.conf文件五、修改默认存储路径六、配置防火墙七、生产环境优化(待完善)八、启用SSL加密(待验证)九…...
如何在gitlab上使用hooks
参考链接:gitlab git hooks 1. Git Hook 介绍 与许多其他版本控制系统一样,Git 有一种方法可以在发生某些重要操作时,触发自定义脚本,即 Git Hook(Git 钩子)。 当我们初始化一个项目之后,.git…...
【点云surface】 凹包重构
1 处理过程可视化 原始数据 直通滤波过滤后 pcl::ProjectInliers结果 pcl::ExtractIndices结果 凹包结果 凸包结果 2 处理过程分析: 原始点云 ---> 直通滤波 --> pcl::SACSegmentation分割出平面 -->pcl::ProjectInliers投影 --> pcl::ConcaveHull凹包…...
Linux sed命令
目录 一. 去除单个指定文本的换行符二. 去除多个指定文本的换行符三. 抽取出指定数据3.1 分别抽取SPLREQUEST和SPLEND的数据3.2 通过join命令将文件合并3.3 抽取出指定的数据3.4 去除换行符,整合数据为一行 一. 去除单个指定文本的换行符 👉 info.txt …...
Nginx反向代理实现负载均衡+Keepalive实现高可用
目录 实现负载均衡 实现高可用 实现负载均衡 Nginx的几种负载均衡算法: 1.轮询(默认) 每个请求按照时间顺序逐一分配到下游的服务节点,如果其中某一节点故障,nginx 会自动剔除故障系统使用户使用不受影响。 2.权重…...
实用高效 无人机光伏巡检系统助力电站可持续发展
近年来,我国光伏发电行业规模日益壮大,全球领先地位愈发巩固。为解决光伏电站运维中的难题,浙江某光伏电站与复亚智能达成战略合作,共同推出全自动无人机光伏巡检系统,旨在提高发电效率、降低运维成本,最大…...
智慧工地云平台源码,基于微服务架构+Java+Spring Cloud +UniApp +MySql
智慧工地管理云平台系统,智慧工地全套源码,java版智慧工地源码,支持PC端、大屏端、移动端。 智慧工地聚焦建筑行业的市场需求,提供“平台网络终端”的整体解决方案,提供劳务管理、视频管理、智能监测、绿色施工、安全管…...
FFmpeg 低延迟同屏方案
引言 在实时互动需求激增的当下,无论是在线教育中的师生同屏演示、远程办公的屏幕共享协作,还是游戏直播的画面实时传输,低延迟同屏已成为保障用户体验的核心指标。FFmpeg 作为一款功能强大的多媒体框架,凭借其灵活的编解码、数据…...
HDFS分布式存储 zookeeper
hadoop介绍 狭义上hadoop是指apache的一款开源软件 用java语言实现开源框架,允许使用简单的变成模型跨计算机对大型集群进行分布式处理(1.海量的数据存储 2.海量数据的计算)Hadoop核心组件 hdfs(分布式文件存储系统)&a…...
Spring AI Chat Memory 实战指南:Local 与 JDBC 存储集成
一个面向 Java 开发者的 Sring-Ai 示例工程项目,该项目是一个 Spring AI 快速入门的样例工程项目,旨在通过一些小的案例展示 Spring AI 框架的核心功能和使用方法。 项目采用模块化设计,每个模块都专注于特定的功能领域,便于学习和…...
如何在Windows本机安装Python并确保与Python.NET兼容
✅作者简介:2022年博客新星 第八。热爱国学的Java后端开发者,修心和技术同步精进。 🍎个人主页:Java Fans的博客 🍊个人信条:不迁怒,不贰过。小知识,大智慧。 💞当前专栏…...
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
文章目录 1. 题目描述1.1 链表节点定义 2. 理解题目2.1 问题可视化2.2 核心挑战 3. 解法一:HashSet 标记访问法3.1 算法思路3.2 Java代码实现3.3 详细执行过程演示3.4 执行结果示例3.5 复杂度分析3.6 优缺点分析 4. 解法二:Floyd 快慢指针法(…...
文件上传漏洞防御全攻略
要全面防范文件上传漏洞,需构建多层防御体系,结合技术验证、存储隔离与权限控制: 🔒 一、基础防护层 前端校验(仅辅助) 通过JavaScript限制文件后缀名(白名单)和大小,提…...
【若依】框架项目部署笔记
参考【SpringBoot】【Vue】项目部署_no main manifest attribute, in springboot-0.0.1-sn-CSDN博客 多一个redis安装 准备工作: 压缩包下载:http://download.redis.io/releases 1. 上传压缩包,并进入压缩包所在目录,解压到目标…...
leetcode_69.x的平方根
题目如下 : 看到题 ,我们最原始的想法就是暴力解决: for(long long i 0;i<INT_MAX;i){if(i*ix){return i;}else if((i*i>x)&&((i-1)*(i-1)<x)){return i-1;}}我们直接开始遍历,我们是整数的平方根,所以我们分两…...
AWS vs 阿里云:功能、服务与性能对比指南
在云计算领域,Amazon Web Services (AWS) 和阿里云 (Alibaba Cloud) 是全球领先的提供商,各自在功能范围、服务生态系统、性能表现和适用场景上具有独特优势。基于提供的引用[1]-[5],我将从功能、服务和性能三个方面进行结构化对比分析&#…...
