Spring+SpringMVC介绍+bean实例化+依赖注入实战
Spring介绍
Spring是一个轻量级的Java 开发框架,核心是IOC(控制反转)和AOP(面向切面编程)
Spring解决了业务层(Service包)与其他各层(表现层,包括Model,View,Controller三部分;持久层,jdbc和mybatis……)之间耦合度高的问题
耦合是什么?Spring如何解决高耦合的?
耦合是什么?
耦合是衡量程序模块之间互相依赖程度的指标
耦合也可以用来衡量程序拓展性和维护性
这里的依赖,不是继承关系的那种依赖
本质上指的是模块之间关联关系强弱(属性直接获取修改;直接调用方法;通过方法参数调用;使用同一全局变量;使用同一其他模块;参数为一部分成员变量……)
松耦合代表业务层和其他层之间的耦合度较低,互相依赖的程度较低,彼此之间影响小;
松耦合代表业务层和其他层之间的耦合度较高,互相依赖的程度较高,修改A的代码,B也要修改;
我们开发程序,一般都是以“高内聚,低耦合”为目标的
Spring如何解决高耦合
没有Spring之前,我们使用Servlet,JSP和JDBC作为Java开发框架,开发JavaWeb程序
JSP将业务层和视图层耦合在了一起,JDBC又将业务层和持久层耦合在了一起
Spring解决了这个问题,其中的关键在于IOC,将创建对象,使用对象,销毁对象的权力交给SpringBean容器而不是代码
IOC的关键在于DI(依赖注入)
SpringMVC简介
Model(entity包)-View(thymeleaf等视图引擎)-Controller(Controller包)
Model(模型):用来处理程序中数据逻辑的部分
View(视图):在应用程序中,专门和浏览器进行交互,展示数据的资源
Contreller(控制器):可以理解成是一个分发器,来决定对于视图发来的请求,需要用哪一个模型来处理,以及处理完后需要跳回到哪一个视图,也就是用来连接视图和模型的
Spring框架的特点
- 方便解耦,简化开发,Spring就是一个大工厂,可以将所有对象创建和依赖关系维护,交给Spring管理。IOC的作用。
- AOP编程的支持,Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能。(可扩展性)
- 声明式事务的支持,只需要通过配置就可以完成对事务的管理,而无需手动编程。
- 方便程序的测试,Spring对Junit4支持,可以通过注解方便的测试Spring程序。
- 方便集成各种优秀框架,Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts2、Hibernate、MyBatis、Quartz等)的直接支持。
- 降低JavaEE API的使用难度,Spring 对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封装,使这些API应用难度大大降低。
IOC简介
IOC – Inverse of Control,控制反转,将对象的创建权力反转给Spring框架!!
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。
解决问题:使用IOC可以解决的程序耦合性高的问题。Spring的工厂读取配置文件。
IOC创建的bean,默认情况下整个内存只有一份,也就是单例模式,后续的测试中可以看到这一点
IOC是思想,DI是IOC的实现方法,两者绑定
bean的实例化
准备工作
maven依赖
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies>
service接口
public interface UserService {public void hello();}
service接口实现类
public class UserServiceImpl implements UserService {@Overridepublic void hello() {System.out.println("Hello IOC!!");}
}
resources下创建applicationContext.xml配置文件
?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"></beans>
通过applicationContext.xml的方式实例化
1. 直接实例化
?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"><!--IOC管理bean--><!--1. 直接实例化--><bean id="userService" class="cn.tx.service.UserServiceImpl" /></beans>
缺点:当需要加载到bean容器中的bean数量太多的时候,这样一个一个导入非常繁琐
2. 静态bean工程实例化
需要一个静态工厂类
public class StaticBeanFactory {// 静态工厂方式public static UserService staticBeanCreate() {System.out.println("通过静态工厂的方式创建UserServiceImpl对象...");return new UserServiceImpl();}}
随后在xml文件中导入静态工厂bean对象即可
?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="staticUs" class="com.qcby.mySpring01.beanFactory.StaticBeanFactory" factory-method="staticBeanCreate"/>
</beans>
3. 动态工厂实例化
public class DynamicBeanFactory {//对象方法public UserService dynamicBeanCreate(){System.out.println("动态工厂的方式创建bean对象。。。");return new UserServiceImpl();}
}
?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="dynamicFactoryBean" class="com.qcby.mySpring01.beanFactory.DynamicBeanFactory"/><bean id="dynamicUs" factory-bean="dynamicFactoryBean" factory-method="dynamicBeanCreate"/>
</beans>
通过注解实例化
@Component
@Service
@Repository
@Controller
@Mapper
bean实例化测试
public class IOCTest {@Testpublic void run() {ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");
/* ApplicationContext applicationContext =new FileSystemXmlApplicationContext("D:\\6_WorkSpace\\shiXun\\spring01\\src\\main\\resources\\applicationContext.xml");*/UserService userService = (UserService) applicationContext.getBean("userService");UserService userService1 = (UserService) applicationContext.getBean("userService");System.out.println(userService);System.out.println(userService1);userService.hello("IOC!");}@Testpublic void factoryBeanTest() {ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");UserService staticBean = (UserService) applicationContext.getBean("staticUs");UserService dynamicBean = (UserService) applicationContext.getBean("dynamicUs");staticBean.hello("staticFactory");dynamicBean.hello("dynamicFactory");}
}
依赖注入
DI:Dependency Injection,依赖注入,在Spring框架负责创建Bean对象时(bean实例化),
动态的将依赖对象(对象的属性)注入到Bean组件中
通过applicationContext.xml的方式注入
set方法注入
必须保证setter方法存在,否则会报错
public class CarServiceImpl implements CarService {private CarDao carDao;@Overridepublic String toString() {return "CarServiceImpl{" +"msg='" + msg + '\'' +", id=" + id +'}';}private String msg;private Integer id;public void setMsg(String msg) {this.msg = msg;}public void setId(Integer id) {this.id = id;}public void setCarDao(CarDao carDao) {this.carDao = carDao;}public List<Car> findAll() {List<Car> carList = carDao.findAll();return carList;}
}
<!--set方法DI注入--><bean id="carDao" class="com.qcby.mySpring01.mapper.impl.CarDaoImpl"><property name="dataSource" ref="dataSource"/></bean><bean id="carService" class="com.qcby.mySpring01.service.impl.CarServiceImpl"><property name="carDao" ref="carDao"/><property name="msg" value="你好"/><property name="id" value="100"/></bean>
构造方法注入
public class Car {private int id;private String carName;private int size;private String color;public Car() {}public Car(String carName, int size, String color) {this.carName = carName;this.size = size;this.color = color;}@Overridepublic String toString() {return "Car{" +"id=" + id +", carName='" + carName + '\'' +", size=" + size +", color='" + color + '\'' +'}';}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getCarName() {return carName;}public void setCarName(String carName) {this.carName = carName;}public int getSize() {return size;}public void setSize(int size) {this.size = size;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}
}
<!--构造器DI注入--><bean id="car1" class="com.qcby.mySpring01.pojo.Car"><!-- <constructor-arg index="0" value="小米Su7 Pro Max"/><constructor-arg index="1" value="10"/><constructor-arg index="2" value="blue"/>--><constructor-arg name="carName" value="小米Su7 Pro Max"/><constructor-arg name="size" value="10"/><constructor-arg name="color" value="blue"/></bean><bean id="car2" class="com.qcby.mySpring01.pojo.Car"><!-- <constructor-arg index="0" value="小米Su7 Pro Max"/><constructor-arg index="1" value="10"/><constructor-arg index="2" value="blue"/>--><constructor-arg name="carName" value="BYD秦PLUS DMI"/><constructor-arg name="size" value="198"/><constructor-arg name="color" value="black"/></bean>
通过接口注入
(暂时略,后续补充)
数组,集合(List,Set,Map),Properties等的注入
public class CollectionBean {// 数组private Student[] studentArr;public void setStudentArr(Student[] studentArr) {this.studentArr = studentArr;}private List<String> list;public void setList(List<String> list) {this.list = list;}private Map<String, String> map;public void setMap(Map<String, String> map) {this.map = map;}private Map<Student, Car> studentCarMap;public void setStudentCarMap(Map<Student, Car> studentCarMap) {this.studentCarMap = studentCarMap;}private Properties properties;public void setProperties(Properties properties) {this.properties = properties;}@Overridepublic String toString() {return "CollectionBean{" +"studentArr=" + Arrays.toString(studentArr) +", list=" + list +", map=" + map +", studentCarMap=" + studentCarMap +", properties=" + properties +'}';}
}
<!--引用类型/集合注入--><bean id="student1" class="com.qcby.mySpring01.pojo.Student"><property name="name" value="张三"/><property name="age" value="15"/><property name="grade" value="7"/></bean><bean id="student2" class="com.qcby.mySpring01.pojo.Student"><property name="name" value="李四"/><property name="age" value="14"/><property name="grade" value="6"/></bean><bean id="student3" class="com.qcby.mySpring01.pojo.Student"><property name="name" value="王五"/><property name="age" value="18"/><property name="grade" value="13"/></bean><bean id="collectionBean" class="com.qcby.mySpring01.pojo.CollectionBean"><property name="studentArr"><array><ref bean="student1"/><ref bean="student2"/><ref bean="student3"/></array></property><property name="list"><list><value>熊大</value><value>熊二</value><value>吉吉国王</value></list></property><property name="map"><map><entry key="111" value="aaa"/><entry key="222" value="bbb"/></map></property><property name="studentCarMap"><map><entry key-ref="student1" value-ref="car1"/><entry key-ref="student2" value-ref="car2"/></map></property><property name="properties"><props><prop key="username">root</prop><prop key="password">123456</prop></props></property></bean>
这些其实都是固定写法
测试
@Testpublic void DITest() {ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");CarService carService = (CarService) applicationContext.getBean("carService");// set方法注入System.out.println(carService);List<Car> carList = carService.findAll();for (Car car : carList) {System.out.print(car.getCarName() + "\t");}System.out.println();// 构造方法注入Car car1 = (Car) applicationContext.getBean("car1");System.out.println(car1);// 数组,集合(List,Set,Map),Properties注入CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean");System.out.println(collectionBean);}
通过注解注入
依赖注入常用的注解
@Value 用于注入普通类型(String,int,double等类型)
@Autowired 默认按类型进行自动装配(引用类型)
@Qualifier 和@Autowired一起使用,强制使用名称注入
@Resource Java提供的注解,也被支持。使用name属性,按名称注入
对象生命周期(作用范围)注解
@Scope 生命周期注解,取值singleton(默认值,单实例)和prototype(多例)
初始化方法和销毁方法注解(了解)
@PostConstruct 相当于init-method
@PreDestroy 相当于destroy-method
@Service
@Qualifier("studentServiceImpl")
public class StudentServiceImpl implements StudentService {public void listAll() {System.out.println("studentService2");}
}
@Service
@Qualifier("studentServiceImpl2")
public class StudentServiceImpl2 implements StudentService {public void listAll() {System.out.println("studentService2");}
}
@Configuration
@ComponentScan("com.qcby")
@Import({SpringConfig2.class})// 多配置文件
public class SpringConfig {}
@Testpublic void qualifierTest() {ApplicationContext applicationContext =new AnnotationConfigApplicationContext(SpringConfig.class);
// ApplicationContext applicationContext =
// new ClassPathXmlApplicationContext("applicationContext_anno.xml");
/* ApplicationContext applicationContext =new FileSystemXmlApplicationContext("D:\\6_WorkSpace\\shiXun\\spring01\\src\\main\\resources\\applicationContext_anno.xml");*/StudentService studentService = (StudentService) applicationContext.getBean("studentServiceImpl");StudentService studentService2 = (StudentService) applicationContext.getBean("studentServiceImpl2");System.out.println(studentService);System.out.println(studentService2);studentService.listAll();studentService2.listAll();}
纯注解不需要写applicationContext.xml文件
相关文章:

Spring+SpringMVC介绍+bean实例化+依赖注入实战
Spring介绍 Spring是一个轻量级的Java 开发框架,核心是IOC(控制反转)和AOP(面向切面编程) Spring解决了业务层(Service包)与其他各层(表现层,包括Model,Vie…...

【安装笔记-20240616-Linux-为 OpenWrt 自动挂载 Windows 主机共享目录】
安装笔记-系列文章目录 安装笔记-20240616-Linux-为 OpenWrt 自动挂载 Windows 主机共享目录 文章目录 安装笔记-系列文章目录安装笔记-20240616-Linux-为 OpenWrt 自动挂载 Windows 主机共享目录 前言一、软件介绍名称:cifsutils主页官方介绍特点 二、安装步骤测试…...

61.WEB渗透测试-信息收集- WAF、框架组件识别(1)
免责声明:内容仅供学习参考,请合法利用知识,禁止进行违法犯罪活动! 内容参考于: 易锦网校会员专享课 上一个内容:60.WEB渗透测试-信息收集- 端口、目录扫描、源码泄露(8) WAF的识…...

qmt量化交易策略小白学习笔记第45期【qmt编程之期货行情数据--如何获取日线行情、tick行情】
qmt编程之获取期货行情数据 qmt更加详细的教程方法,会持续慢慢梳理。 也可找寻博主的历史文章,搜索关键词查看解决方案 ! 感谢关注,咨询免费开通量化回测与获取实盘权限,欢迎和博主联系! 获取日线行情数…...
c#default 运算符
值类型默认值boolfalsebyte0char‘\0’decimal0.0Mdouble0.0Denum表达式 (E)0 产生的值,其中 E 为 enum 标识符。float0.0Fint0long0Lsbyte0short0struct将所有的值类型字段设置为默认值并将所有的引用类型字段设置为 null 时产生的值。uint0ulong0ushort0引用类型n…...

25计算机考研,这所985有机会!
吉林大学的计算机学科评估是A-,软件是B 实力还是很强的! 考研的专科课代码分别是941和966 其实就是自命题,941是四合一:数据结构,计算机组成与设计,操作系统和计算机网络,这个和408统考的科目…...
SQL 基础入门教程
目录 什么是 SQL? SQL 的基本操作 数据库的创建和删除 表的创建和删除 数据的插入 数据的查询 数据的更新 数据的删除 SQL 的高级操作 表的连接 聚合函数 分组和排序 子查询 视图 索引 SQL 的数据完整性和约束 总结 SQL(Structured Que…...
<Python><paddleocr>基于python使用百度paddleocr实现图片文字识别与替换
前言 本文是使用百度的开源库paddleocr来实现对图片文字的识别,准确度还不错,对图片文字的替换,则利用opencv来完成。 环境配置 系统:windows 平台:visual studio code 语言:python 库:paddleocr、opencv、pyqt5 依赖库安装 本例所需要的库可以直接用pip来安装。 安装…...
小程序开发的费用简介篇
小程序的价格跟很多因素有关系,比如你想要的复杂度、功能多不多等等 今天我就来具体说说开发一款APP/小程序到底需要多少 ❶功能复杂度:功能越多越复杂,开发时间和费用就越高,费用就会高 ❷设计要求:高级的…...
torch.unflod与torch.nn.functional.pad用法
PyTorch 中的两个函数:torch.unfold 和 torch.nn.unfold。它们分别用于不同的目的,让我们分别来理解一下: torch.nn.Unfold 类功能: 类似于函数 torch.unfold,torch.nn.Unfold 类也用于沿着指定维度滑动提取窗口并将每个窗口展平。与函数不同的是,torch.nn.Unfold 是一个…...
江苏 服务器性能监控包含哪些方面?
服务器的性能监控主要是为了确保服务器能够正常运行工作和性能优化的重要手段,接下来就来看一下服务器性能监控所包含的内容有哪些吧! 首先对于服务器的系统资源进行一定的监控,CPU作为服务器的核心组件之一,所以我们要监控CPU的使…...

卓越的 App UI 风格引领潮流
卓越的 App UI 风格引领潮流...

BirdTalk IM集群中消息流转策略讨论
BirdTalk IM集群中消息流转策略讨论 目前群聊的存储策略是1写多读方案;每个群组一个队列,按时间顺序排列,不区分用户; 私聊的存储是写扩散的,每个人都有自己的消息队列,按时间顺序 保存所有的消息&#x…...

重磅!2024年最新影响因子正式发布,附Excel下载
大家好,这里是专注表观组学十余年,领跑多组学科研服务的易基因。 激动人心的时刻终于来了,2024年影响因子已全面发布!废话不多说,大家一起来看看最新的发布的结果吧! 神刊:CA-A CANCER JOURNA…...

【会议征稿】2024年应用计算智能、信息学与大数据国际会议(ACIIBD 2024,7月26-28)
2024年应用计算智能、信息学与大数据国际学术会议(ACIIBD 2024)将于2024年7月26-28日在中国广州举办。会议将聚焦于计算智能及其应用、信息、大数据等相关的研究领域, 广泛邀请国内外知名专家学者,共同探讨相关学科领域的最新发展…...

【代码发布】Quantlab4.3:lightGBM应用于全球大类资产的多因子智能策略(代码+数据)
原创文章第566篇,专注“AI量化投资、世界运行的规律、个人成长与财富自由"。 昨天,Quantlab整合Alpha158因子集,为机器学习大类资产配置策略做准备(代码数据),我们完成了因子集构建,并尝试…...

【毕业设计】Django 校园二手交易平台(有源码+mysql数据)
此项目有完整实现源码,有需要请联系博主 Django 校园二手交易平台开发项目 项目选择动机 本项目旨在开发一个基于Django的校园二手交易平台,为大学生提供一个安全便捷的二手物品买卖平台。该平台将提供用户注册和认证、物品发布和搜索、交易信息管理等…...

文章自动生成器,在线AI写作工具
随着人工智能AI技术的发展,AI技术被应用到越来越多的场景。对于需要创作内容的同学来说,AI写作-文章内容自动生成器是一个非常好的辅助工具。AI写作工具可以提升我们的创作效率,快速的生成文章,然后在根据需求进行调整修改即可。下…...

Matlab初识:什么是Matlab?它的历史、发展和应用领域
目录 一、什么是Matlab? 二、Matlab的历史与发展 三、Matlab的应用领域 四、安装和启动Matlab 五、界面介绍 六、第一个Matlab程序 七、总结 一、什么是Matlab? Matlab 是由 MathWorks 公司开发的一款用于数值计算、可视化以及编程的高级技术计算…...

大模型之-Seq2Seq介绍
大模型之-Seq2Seq介绍 1. Seq2Seq 模型概述 Seq2Seq(Sequence to Sequence)模型是一种用于处理序列数据的深度学习模型,常用于机器翻译、文本摘要和对话系统等任务。它的核心思想是将一个输入序列转换成一个输出序列。 Seq2Seq模型由两个主…...
基于算法竞赛的c++编程(28)结构体的进阶应用
结构体的嵌套与复杂数据组织 在C中,结构体可以嵌套使用,形成更复杂的数据结构。例如,可以通过嵌套结构体描述多层级数据关系: struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…...

微信小程序之bind和catch
这两个呢,都是绑定事件用的,具体使用有些小区别。 官方文档: 事件冒泡处理不同 bind:绑定的事件会向上冒泡,即触发当前组件的事件后,还会继续触发父组件的相同事件。例如,有一个子视图绑定了b…...
基于服务器使用 apt 安装、配置 Nginx
🧾 一、查看可安装的 Nginx 版本 首先,你可以运行以下命令查看可用版本: apt-cache madison nginx-core输出示例: nginx-core | 1.18.0-6ubuntu14.6 | http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages ng…...
电脑插入多块移动硬盘后经常出现卡顿和蓝屏
当电脑在插入多块移动硬盘后频繁出现卡顿和蓝屏问题时,可能涉及硬件资源冲突、驱动兼容性、供电不足或系统设置等多方面原因。以下是逐步排查和解决方案: 1. 检查电源供电问题 问题原因:多块移动硬盘同时运行可能导致USB接口供电不足&#x…...
Spring Boot面试题精选汇总
🤟致敬读者 🟩感谢阅读🟦笑口常开🟪生日快乐⬛早点睡觉 📘博主相关 🟧博主信息🟨博客首页🟫专栏推荐🟥活动信息 文章目录 Spring Boot面试题精选汇总⚙️ **一、核心概…...

NFT模式:数字资产确权与链游经济系统构建
NFT模式:数字资产确权与链游经济系统构建 ——从技术架构到可持续生态的范式革命 一、确权技术革新:构建可信数字资产基石 1. 区块链底层架构的进化 跨链互操作协议:基于LayerZero协议实现以太坊、Solana等公链资产互通,通过零知…...
IP如何挑?2025年海外专线IP如何购买?
你花了时间和预算买了IP,结果IP质量不佳,项目效率低下不说,还可能带来莫名的网络问题,是不是太闹心了?尤其是在面对海外专线IP时,到底怎么才能买到适合自己的呢?所以,挑IP绝对是个技…...
Go语言多线程问题
打印零与奇偶数(leetcode 1116) 方法1:使用互斥锁和条件变量 package mainimport ("fmt""sync" )type ZeroEvenOdd struct {n intzeroMutex sync.MutexevenMutex sync.MutexoddMutex sync.Mutexcurrent int…...
数据库正常,但后端收不到数据原因及解决
从代码和日志来看,后端SQL查询确实返回了数据,但最终user对象却为null。这表明查询结果没有正确映射到User对象上。 在前后端分离,并且ai辅助开发的时候,很容易出现前后端变量名不一致情况,还不报错,只是单…...

动态规划-1035.不相交的线-力扣(LeetCode)
一、题目解析 光看题目要求和例图,感觉这题好麻烦,直线不能相交啊,每个数字只属于一条连线啊等等,但我们结合题目所给的信息和例图的内容,这不就是最长公共子序列吗?,我们把最长公共子序列连线起…...