Spring
1.Spring
1、1spring 简介
核心宗旨:简化服务器开发
- Spring:春天---->可以理解为给软件行业带来了春天
- 2002,Rod Jahnson 首次推出了 spring 框架的雏形
- 2004,三月二十四号诞生
- spring 框架是以 interface21 框架为基础,经过重新设计,并且不断丰富其内涵,于 2004 年 3 月 24 日发布了 1.0 的正式版本
- Spring 框架的创始人,同时也是 SpringSource 的联合创始人。Spring 是面向切面编程(AOP)和控制反转(IoC)的容器框架。Rod 的畅销书 Expert One-on-One J2EE Design and Development(2002 年出版)是迄今为止 J2EE 领域最具影响力的书之一。
- spring 理念,使用现有技术更加容易使用,本身是一个大杂烩,整合了现有技术的框架
- SSH:Stuct2+spring+hibernate
- SSM:SpringMvc+Spring+Mybatis
官方下载地址:https://repo.spring.io/release/org/springframework/spring/
Github:https://github.com/spring-projects/spring-framework
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
1.2、优点
- Spring 是一个开源免费的框架(容器)!
- Spring 是一个轻量级的,非入侵式的框架!
- 控制反转(ioc),面向切面变成(AOP)
- 支持事务的处理,对框架整合的支持
总结一句话,Spring 就是一个轻量级的控制反转(ioc)和面向切面(AOP)变成的框架
1.3、组成
每个模块的作用如下:
核心容器(Spring Core):核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转 (IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
Spring 上下文(Spring Context):Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI(Java 命名和目录接口)、EJB(Enterprise Java Beans 称为 Java 企业 Bean)、电子邮件、国际化、校验和调度功能。
Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向方面的编程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何对象支持 AOP。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖 EJB 组件,就可以将声明性事务管理集成到应用程序中。
Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写 的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP。
1.4、拓展
在 Spring 官网有这样一个介绍:现代化的 java 开发!现在的开发说白了就是 spring 开发
-
SpringBoot
- 一个快速开发的脚手架。
- 可以基于 SrpingBoot 可快速开发单个微服务。
- 约定大于配置!
-
SpringCloud
- SpringCloud 是基于 SpringBoot 实现的
应为大多数公司都在使用 SpringBoot 进行快速开发,学习 SpringBoot 的前提是需要完全掌握 Spring 及 SpringMvc,承上启下的作用
弊端:发展了太久之后违背了原来的理念,配置十分繁琐,人称配置地狱
2、IOC 理论推导
2.1 主要是转变思维:只要是学习这个想法
曾经的开发步骤:
- UserDAO 接口
- UserDAOimpl 实现类
- UserService 业务接口
- UserServiceimpl 业务实现类
ioc 是一种思想,在我们之前的业务中,用户的需求,可能会影响我们的源代码,我们需要根据用户的需求去修改代码,如果程序代码量十分大,修改一次的成本代价十分昂贵
我们用一个 Set 接口实现,
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO){
this.userDAO = userDAO;
}
public void getUser() {
userDAO.getUser();
}
}
革命性质的变化,
- 之前,程序是主动创建对象!控制权在程序员手上
- 修改使用 Set 注入后,程序不在具有主动性,而是变成了被动接受对象
控制反转。就是这个思想,从主动变成被动的反转,这种思想从本质上解决了问题,我们程序员不用在去管理程序对象的创建了。系统的耦合性大大降低,可以更加专注的在业务的实现上
2.2ioc 本质
控制反转 IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现 IoC 的一种方法,也有人认为 DI 只是 IoC 的另一种说法。没有 IoC 的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
IoC 是 Spring 框架的核心内容,使用多种方式完美的实现了 IoC,可以使用 XML 配置,也可以使用注解,新版本的 Spring 也可以零配置实现 IoC。
Spring 容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从 Ioc 容器中取出需要的对象。
采用 XML 方式配置 Bean 的时候,Bean 的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean 的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML 或注解)并通过第三方去生产或获取特定对象的方式。在 Spring 中实现控制反转的是 IoC 容器,其实现方法是依赖注入(Dependency Injection,DI)。
3、helloSpring
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cF6lKXIb-1648917346642)(https://gitee.com/cold-abyss_admin/my-image-host/raw/master/%20img%20/%E6%9C%AA%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6%20(1)].png)
3.1、导入 Jar 包
注 : spring 需要导入 commons-logging 进行日志记录 . 我们利用 maven , 他会自动下载对应的依赖项 .
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
3.2、编写代码
-
编写一个 Hello 实体类
package com.hyc.pojo;
public class test {
@Override
public String toString() {
return "test{" +
"str='" + str + '\'' +
'}';
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
private String str;
} -
编写我们的 spring 文件 , 这里我们命名为 beans.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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在Spring这些都成为Bean
平时 类型 变量名 = new 类型()
test ts = new test();
Spring中
id = 变量名
class = new 对象
bean = 对象 相当于 new test();
property 相当于给对象中的属性设置一个值
以来set注入
-->
<bean id="hello" class="com.hyc.pojo.test">
<property name="str" value="Spring"></property>
</bean>
</beans> -
我们可以去进行测试了 .
import com.hyc.pojo.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MuTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在Spring中管理,要使用直接取出来就可以了
test hello = (test)context.getBean("hello");
System.out.println(hello.toString());
}
}
3.3、思考
- test 对象是谁创建的 ? 【 hello 对象是由 Spring 创建的 】
- test 对象的属性是怎么设置的 ? 【hello 对象的属性是由 Spring 容器设置的 】
这个过程就叫控制反转 :
- 控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用 Spring 后 , 对象是由 Spring 来创建的
- 反转 : 程序本身不创建对象 , 而变成被动的接收对象 .
依赖注入 : 就是利用 set 方法来进行注入的.
==IOC 是一种编程思想,由主动的编程变成被动的接收==
可以通过 newClassPathXmlApplicationContext 去浏览一下底层源码 .
3.4、修改案例一
我们在案例一中, 新增一个 Spring 配置文件 beans.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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在Spring这些都成为Bean
平时 类型 变量名 = new 类型()
test ts = new test();
Spring中
id = 变量名
class = new 对象
bean = 对象 相当于 new test();
property 相当于给对象中的属性设置一个值
依赖set注入
-->
<bean id="mysqlimpl" class="com.hyc.dao.UserMysqlIMPL"></bean>
<bean id="hi" class="com.hyc.dao.UserDaoImpl"></bean>
<bean id="usService" class="com.hyc.Service.UserServiceImpl">
<!-- ref 引用Spring容器中创建好的对象
value: 具体的值,基本类型使用
-->
<property name="userDAO" ref="mysqlimpl"></property>
</bean>
</beans>
测试!
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext拿到Spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//有容器,天下我有,老子要什么就有什么
UserServiceImpl usService =(UserServiceImpl) context.getBean("usService");
usService.getUser();
}
}
OK , 到了现在 , 我们彻底不用再程序中去改动了 , 要实现不同的操作 , 只需要在 xml 配置文件中进行修改 , 所谓的 IoC,一句话搞定 : 对象由 Spring 来创建 , 管理 , 装配 !
4.IOC 创建对象的方式
-
使用无参构造创建对象,默认
-
使用有参的方法,假设我们要用有参构造创建对象
-
下标赋值
<!-- 第一种 下标赋值-->
<bean id="user" class="com.hyc.pojo.User">
<constructor-arg index="0" value="胡宇辰"></constructor-arg>
</bean> -
类型赋值(不推荐)
<!--通过类型创建-->
<bean id="user" class="com.hyc.pojo.User">
<!-- <constructor-arg index="0" value="胡宇辰"></constructor-arg>-->
<constructor-arg type="java.lang.String" value="胡宇辰"></constructor-arg>
</bean> -
通过变量名来赋值
<!--第三种,通过参数名来赋值-->
<bean id="user" class="com.hyc.pojo.User">
<constructor-arg name="name" value="胡宇辰"></constructor-arg>
</bean>
-
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!
5、Spring 配置
5.1、别名
<!-- 别名:如果添加了别名我们也可以使用别名去获取类-->
<alias name="user" alias="usersss"></alias>
5.2、Bean 的配置、
<!--
id:bean的唯一标识符,相当于我们的对象名
class:bean对象所对应的全限定名:包名+类名
name:也是别名
-->
<bean id="UserT" class="com.hyc.pojo.User2" name="lz"></bean>
5.3import
这个 import,一般用于团队开发使用,可以将多个配置文件导入合并为一个
假设,有多个人开发一个项目,这三个人负责不同的类开发,不同的类需要注册在不同的 bean 中偶们可以 import 将所有人的 beans,xml 合并成一个总的
- 张三
- 李四
- 王五
- 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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
</beans>
6.DI 依赖注入、
6.1 构造器注入
前面已经讲了
6.2、Set 方式注入
- 依赖注入:Set 注入
- 依赖:bean 对象的创建依赖于容器
- 注入:bean 对象中的所有属性由容器来注入
【环境搭建】
-
复杂类型
private String address;
public Address() {
}
public Address(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address =address;
} -
真实测试对象
private String name;
private Address address;
private String[]books;
private List<String>hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info; -
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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.hyc.pojo.Student">
<property name="name" value="hyc"></property>
</bean>
</beans> -
测试类
import com.hyc.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
6.3 拓展方式注入
我们可以使用 p 命名和 c 命名空间来进行注入
官方解释:
<!--p命名空间注入,可以直接注入属性的,本质是setter-->
<bean id="user" class="com.hyc.pojo.User" p:name="qing" p:age="18">
</bean>
<!--c命名空间注入,通过构造器注入 本质是构造器-->
<bean id="user2" class="com.hyc.pojo.User" c:name="胡宇辰" c:age="19"></bean>
测试:
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
User user = context.getBean("user", User.class);
System.out.println(user);
}
注意点:
p 和 c 命名空间不能直接使用,需要导入 xml 约束,才能使用
xmlns:p="http://www.springframework.org/schema/p"
6.4、bean 的作用于
Scope | Description |
---|---|
singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext . |
session | Scopes a single bean definition to the lifecycle of an HTTP Session . Only valid in the context of a web-aware Spring ApplicationContext . |
application | Scopes a single bean definition to the lifecycle of a ServletContext . Only valid in the context of a web-aware Spring ApplicationContext . |
websocket | Scopes a single bean definition to the lifecycle of a WebSocket . Only valid in the context of a web-aware Spring ApplicationContext |
-
代理模式(Spring 默认机制)
<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
-
原型模式:每次从容器中 get 的时候,都会产生一个新的对象!他们的 hashcode 是不相等的
-
其余的只在 web 开发中使用到
7.Bean 的自动装配
- 自动装配是 Spring 满足 Bean 依赖的一种方式
- Spring 会在上下文中自动寻找,并且自动给 bean 装配属性
在 spring 中有三种自动装配的方式
- 在 xml 显示的配置
- 在 java 中的显示配置
- 隐式的自动装配 bean【重要】
7.1、测试
环境搭建一个人有两个宠物
7.2、自动装配
Byname:byName:会自动在容器上下文中查找,和自己对象 set 的对应的值 beanid
<bean id="perple" class="com.hyc.pojo.Perple" autowire="byName">
<property name="name" value="Hyc"></property>
</bean>
ByType:byType:会自动在容器上下文中查找,和自己对象同属性的相同的 bean
<bean id="perple" class="com.hyc.pojo.Perple" autowire="byType">
<property name="name" value="Hyc"></property>
</bean>
小结:
- byname 的时候需要保证所有 bean 的 id 唯一,并且这个 bean 需要和自动注入的属性的 set 方法一致
- bytype 的时候需要保证所有 bean 的 class 唯一,并且这个 bean 需要和自动注入的属性的类型一致
7.3、使用注解实现自动装配
jdk1.5 支持的注解,Spring2.5 就支持注解了
要使用注解须知:
-
导入约束:CONTEXT 约束
-
配置注解支持:context:annotation-config/【重要】
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/beans/spring-context.xsd
"> </beans>
@Autowired
直接在属性上使用即可,也可以在 set 方法上使用
使用 Autowired 我们可以不用编写 Set 方法,前提是自动装配的属性在 IOC 容器中存在,且命名符合 byname!
科普:
@NULLABLE 字段标记了这个字段,说明这个字段可以为null
public @interface Autowired {
boolean required() default true;
}
//如果显式的定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Qualifier(value ="dog")//自动装配指定id名字
如果@Autowired
自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired
】完成的时候,我们可以使用@Qualifier(value ="xxx")去配置
@Autowired
的使用,指定一个唯一的 bean 对象注入
//如果显式的定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired
private cat cat;
@Autowired
@Qualifier(value ="dog")
private Dog dog;
@Resource 注解
@Resource(name = "cat")
private cat cat;
小结:
@Resoure 和@Autowired 的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Auowired 通过 ByType 的方式实现,而且必须有要求的对象存在【常用】
- @Resource 默认通过 byname 的方式实现,如果找不到名字,则通过 byType 实现,如果两个都找不到,就报错!【常用】
- 执行先后顺序不同:@Auowired 通过 ByType 的方式实现,@Resource 默认通过 byname 的方式实现
8、使用注解开发
在 Spring4 之后,要使用注解开发必须要保证 AOP 的包导入了
导入约束,增加注解约束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/beans/spring-context.xsd ">
</beans>
-
bean
@Component(value = "user")//相当于注册bean,放在类上相当于类被Spring管理
-
属性如何注入
@Value("胡宇辰")相当于
<property name="name" value="胡宇辰"></property> -
衍生的注解
- @Component 有几个衍生注解,我们在 web 开发中,会按照 mvc 三层架构分层
- dao-->[@Repository]
- service-->[@Service]
- controller-->[@Controller]
这四个注解功能都是一样的,都是代表将某个类注册到 Spring 中装配 bean
-
自动装配
- @Auowired通过ByType的方式实现,而且必须有要求的对象存在【常用】
- @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现,如果两个都找不到,就报错!【常用】
-@Component(value = "user")//相当于注册bean,放在类上相当于类被Spring管理 -
作用域
@Scope(scopeName = "singleton")
-
小结
xml 与注解
- xml 更加万能,适用于任何场合!维护简单方便
- 注解不是自己的类使用不了,维护相对复杂
xml 与注解的最佳时间
- xml 用来管理所有的 bean
- 注解负责属性的注入
- 在我们使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
<context:component-scan base-package="com.hyc"></context:component-scan>
<context:annotation-config></context:annotation-config>
9、使用 java 的方式配置 Spring
我们现在要完全不使用 Spring 的 xml 配置了,全权交给 java 来做!
javaConfig 是 Spring 的一个子项目,他是在 Spring4 之后变成了核心功能
配置类
package com.hyc.HycConfig;
import com.hyc.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration//这个也会被Spring容器托管,被注册到容器中,应为本来他就是一个Component,@Configuration代表这是一个配置类,和我们之前的beans。xml是一样的
@ComponentScan("com.hyc")
@Import(HycConfigto02.class)
public class HycConfigto {
//注册一个bean,就相当于是我们之前写的一个bean标签
//这个方法的名字就是bean标签中的id属性
//这个方法的返回值就相当于,bean标签的class
@Bean
public User Getuser(){
return new User();
}
}
实体类
package com.hyc.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这里这个注解的意思是这个类被Spring接管了,注册到了容器中
@Component
public class User {
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
@Value("hyc")
public void setName(String name) {
this.name = name;
}
}
测试类
import com.hyc.HycConfig.HycConfigto;
import com.hyc.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
@Test
public void show(){
//如果完全使用了配置类方式去做,我们就只能通过ApplicationContext上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(HycConfigto.class);
User user = (User) context.getBean("Getuser");
System.out.println(user.getName());
}
}
这种纯 java 配置,在 SpringBoot 随处可见
10、代理模式
中介: 为什么学习代理模式,应为这就是 SpringAOP 的底层,
面向切面编程的底层实现!【SpringAOP 和 SpringMVC】
代理模式分类
- 静态代理
- 动态代理
10.1、静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色,
- 代理角色:代理真实角色后,会做一些附属操作
- 客户:访问代理对象的人!
代理步骤:
-
接口
package com.hyc.demo01;
public interface Rent {
public void rent();
} -
真实角色
package com.hyc.demo01;
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子");
}
} -
代理角色
package com.hyc.demo01;
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
public void rent() {
seeHourse();
host.rent();
hetong();
Fare();
}
public void seeHourse(){
System.out.println("中介带你看房");
}
public void Fare(){
System.out.println("收中介费");
}
public void hetong(){
System.out.println("签租赁合同");
}
} -
客户端访问
package com.hyc.demo01;
public class Client {
public static void main(String[] args) {
//
//房东要租房子,不想自己干活
Host host = new Host();
//中介帮房东租房子,代理角色一般会有一些附属操作
Proxy proxy = new Proxy(host);
//你不用面对房租,直接找总中介租房就可以了
proxy.rent();
}
}
代理模式好处:
- 可以让真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共业务交给代理角色,实现了分工
- 公共业务发生拓展的时候,方便集中管理
缺点:
- 一个真实觉得就会产生一个代理角色,代码量会翻倍,开发效率会变低
10.2、加深理解
代码对应:demo02
AOP 记录
10.3、动态代理
如何改变静态代理的缺点
- 动态代理和静态代理的角色一样
- 动态代理的代理类是动态生成的,不是我们写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 最经典的基于接口:JDK 的动态代理【我们使用这一种】
- 基于类的:cglib
- java 字节码实现:javassist
需要了解两个类:Proxy,InvocationHandler
动态代理的好处:
- 可以让真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共业务交给代理角色,实现了分工
- 公共业务发生拓展的时候,方便集中管理
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
11、AOP
11.1 什么是 AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP 是 OOP 的延续,是软件开发中的一个热点,也是 Spring 框架中的一个重要内容,是函数式编程的一种衍生范型。利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2 Aop 在 Spring 中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ….
- 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知 执行的 “地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP 中,通过 Advice 定义横切逻辑,Spring 中支持 5 种类型的 Advice:
即 Aop 在 不改变原有代码的情况下 , 去增加新的功能 .
11.3 使用 Spring 实现 Aop
【重点】使用 AOP 织入,需要导入一个依赖包!
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --><dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version></dependency>
实现方式一:
使用 SpringAPI 接口实现 AOP【SpringAPI 接口实现】
实现方式二:
自定义来实现 AOP【主要是切面】
实现方式三:
使用注解实现
12、整合 Mybatis
整合步骤:
- 导入相关 jar 包
- 编写配置文件
- 测试
12.1、回忆 Mybatis
- 编写实体类
- 编写核心配置文件
- 编写接口
- 编写 Mapperx.xml
- 测试
12.2、Mybatis-spring
第一种方法:传统 xml 的配制方法
-
编写数据源配置
<!--数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean> -
sqlSessionFactory
<!--sqlsessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/hyc/Mapper/UserMapper.xml"/>
</bean> -
sqlSessionTemplate
<!--SqlSessionTemplate就是我们使用的sqlSeesion-->
<bean id="sqlsession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能使用构造器注入,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean> -
需要给接口加实现类
public class UserMapperImpl implements UserMapper {
//在原来,我们所有的sqlsession来执行,现在我们使用Spring中sqlSessionTemplate
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
} -
将自己写的实现类,注入到 Spring 中
<bean id="UserMapperClass" class="com.hyc.Mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlsession"/>
</bean> -
测试使用即可
@Test
public void test() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserMapper userMapperClass = (UserMapper) context.getBean("UserMapperTwo");
List<User> userList = userMapperClass.selectUser();
for (User user : userList) {
//
System.out.println(user);
}
第二种方法:使用新特性 SqlSessionDaoSupport
-
绑定数据源
<!--数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean> -
sqlSessionFactory
<!--sqlsessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/hyc/Mapper/UserMapper.xml"/>
</bean> -
编写继承 SqlSessionDaoSupport 的类
public class UserMapperTwo extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
return getSqlSession().getMapper(UserMapper.class).selectUser();
}
} -
去 spring 中装配 SqlSessionDaoSupport 支持类注入 sqlSessionFactory
<bean id="UserMapperTwo" class="com.hyc.Mapper.UserMapperTwo">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean> -
测试
public class MyTest {
@Test
public void test() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserMapper userMapperClass = (UserMapper) context.getBean("UserMapperTwo");
List<User> userList = userMapperClass.selectUser();
for (User user : userList) {
//
System.out.println(user);
}
}
}
13、声明式事务
12.1、回顾事务
- 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!
- 事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。
==事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。==
事务四个属性 ACID
- 原子性(atomicity)
- 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用
- 一致性(consistency)
- 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中
- 隔离性(isolation)
- 可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏
- 持久性(durability)
- 事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中
12.2、测试
将上面的代码拷贝到一个新项目中
在之前的案例中,我们给 userDao 接口新增两个方法,删除和增加用户;
//添加一个用户int addUser(User user);//根据id删除用户int deleteUser(int id);
mapper 文件,我们故意把 deletes 写错,测试!
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
deletes from user where id = #{id}
</delete>
编写接口的实现类,在实现类中,我们去操作一波
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper { //增加一些操作
public List<User> selectUser() {
User user = new User(4,"小明","123456");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class); mapper.addUser(user);
mapper.deleteUser(4);
return mapper.selectUser();
}
//新增
public int addUser(User user) {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class); return mapper.addUser(user); }
//删除
public int deleteUser(int id) {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class); return mapper.deleteUser(id); }}
测试
@Testpublic void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);}
报错:sql 异常,delete 写错
结果 :插入成功!
没有进行事务的管理;我们想让他们都成功才成功,有一个失败,就都失败,我们就应该需要事务!
以前我们都需要自己手动管理事务,十分麻烦!
但是 Spring 给我们提供了事务管理,我们只需要配置即可;
12.3、Spring 中的事务管理
Spring 在不同的事务管理 API 之上定义了一个抽象层,使得开发人员不必了解底层的事务管理 API 就可以使用 Spring 的事务管理机制。Spring 支持编程式事务管理和声明式的事务管理。
编程式事务管理
- 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
- 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码
声明式事务管理
- 一般情况下比编程式事务好用。
- 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
- 将事务管理作为横切关注点,通过 aop 方法模块化。Spring 中通过 Spring AOP 框架支持声明式事务管理。
使用 Spring 管理事务,注意头文件的约束导入 : tx
xmlns:tx="http://www.springframework.org/schema/tx"http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd">
事务管理器
- 无论使用 Spring 的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。
- 就是 Spring 的核心事务管理抽象,管理封装了一组独立于技术的方法。
JDBC 事务
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
配置好事务管理器后我们需要去配置事务的通知
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="search*" propagation="REQUIRED"/>
<tx:method name="get" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
spring 事务传播特性:
事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring 支持 7 种事务传播行为:
- propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
- propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
- propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
- propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
- propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
- propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与 propagation_required 类似的操作
Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。
假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。
就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!
配置 AOP
导入 aop 的头文件!
<!--配置aop织入事务-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.kuang.dao.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
进行测试
删掉刚才插入的数据,再次测试!
@Testpublic void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
思考问题?
为什么需要配置事务?
- 如果不配置,就需要我们手动提交控制事务;
- 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!