Spring框架看着一篇就够了!!

Spring框架

一 、Spring 简介

1.1 、Spring概述

官网地址:https://spring.io/

  • Spring 是最受欢迎的企业级 Java 应用程序开发框架,数以百万的来自世界各地的开发人员使用 Spring 框架来创建性能好、易于测试、可重用的代码。
  • Spring 框架是一个开源的 Java 平台,它最初是由 Rod Johnson 编写的,并且于 2003 年 6 月首 次在 Apache 2.0 许可下发布。 Spring 是轻量级的框架,其基础版本只有 2 MB 左右的大小。
  • Spring 框架的核心特性是可以用于开发任何 Java 应用程序,但是在 Java EE 平台上构建 web 应 用程序是需要扩展的。
  • Spring 框架的目标是使 J2EE 开发变得更容易使用,通过启用基于 POJO 编程模型来促进良好的编程实践。

二 、Spring Framework

Spring 基础框架,可以视为 Spring 基础设施,基本上任何其他 Spring 项目都是以 Spring Framework 为基础的。

2.1 Spring Framework特性

  • **非侵入式:**使用 Spring Framework 开发应用程序时,Spring 对应用程序本身的结构影响非常 小。对领域模型可以做到零污染;对功能性组件也只需要使用几个简单的注解进行标记,完全不会 破坏原有结构,反而能将组件结构进一步简化。这就使得基于 Spring Framework 开发应用程序 时结构清晰、简洁优雅。
  • 控制反转:IOC——Inversion of Control,翻转资源获取方向。把自己创建资源、向环境索取资源 变成环境将资源准备好,我们享受资源注入。
  • **面向切面编程:**AOP——Aspect Oriented Programming,在不修改源代码的基础上增强代码功 能。
  • 容器:Spring IOC 是一个容器,因为它包含并且管理组件对象的生命周期。组件享受到了容器化 的管理,替程序员屏蔽了组件创建过程中的大量细节,极大的降低了使用门槛,大幅度提高了开发 效率。
  • **组件化:**Spring 实现了使用简单的组件配置组合成一个复杂的应用。在 Spring 中可以使用 XML 和 Java 注解组合这些对象。这使得我们可以基于一个个功能明确、边界清晰的组件有条不紊的搭 建超大型复杂应用系统。
  • **声明式:**很多以前需要编写代码才能实现的功能,现在只需要声明需求即可由框架代为实现。
  • **一站式:**在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库。而且 Spring 旗下的项目已经覆盖了广泛领域,很多方面的功能性需求可以在 Spring Framework 的基 础上全部使用 Spring 来实现。

2.2 IOC 容器

2.1.1 IOC思想

IOC : Inversion of Control,翻译过来是反转控制

获取资源的传统方式 : 自己做饭:买菜、洗菜、择菜、改刀、炒菜,全过程参与,费时费力,必须清楚了解资源创建整个过程 中的全部细节且熟练掌握。 在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的 模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效 率。

反转控制方式获取资源: 点外卖:下单、等、吃,省时省力,不必关心资源创建过程的所有细节。 反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向——改由容器主 动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源 的方式即可,极大的降低了学习成本,提高了开发的效率。这种行为也称为查找的被动形式。

DI : Dependency Injection,翻译过来是依赖注入。

(依赖 注入: 为当前Spring 中所管理的对象和属性进行赋值)

DI 是实现 IOC的一种方式, 是IOC思想的一种具体实现

简单来说就是 组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器 的资源注入。

当前 依赖哪个对象 ,Spring 就对哪个对象进行赋值

2.1.2 IOC容器在Spring中的实现

IOC 容器中存放的就是Spring 所管理的 对象 (组件) , 如果要管理首先要先创建一个IOC容器, 用来存放组件 . Spring 中提供了两种 实现IOC容器的方式 :

①BeanFactory : 这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。

②ApplicationContext : BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用 ApplicationContext 而不是底层的 BeanFactory。

image-20220820221842545

image-20220820221901352

ClassPathXmlApplicationContext 用的多, 因为一个java工程会打包成一个jar包, 要能够随处运行, 用第二种FileSystemXmlApplicationContext ,在其他电脑上的该路径下不一定有这个文件.

引例 :

  1. 引入依赖
<dependencies>
        <!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.1</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. 在java目录下创建一个 Student 类重写

  2. 配置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/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--
    配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理
    通过bean标签配置IOC容器所管理的bean
    属性:
    id:设置bean的唯一标识
    class:设置bean所对应类型的全类名
-->

    <bean id="studentOne" class="com.ykh.spring.pojo.Student"/>
</beans>

注意! : IOC是通过无参构造来创建对象的, IOC管理的类必须要有无参构造才能创建对象!!

2.1.3获取bean对象的三种方式

写一个测试类

public class IOCByXMLTest {
    @Test
    public void testIOC() {
        //获得容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
        //获取bean对象的第一种方法 : 使用 唯一标识获取
        Student studentOne = (Student)ioc.getBean("studentOne");
        System.out.println(studentOne);
    }
}


public class IOCByXMLTest {
    @Test
    public void testIOC() {
        //获得容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
        //获取bean对象的3种方法 :
        // 1.使用 id 唯一标识获取
        Student bean1 = (Student)ioc.getBean("studentOne");
        System.out.println(bean1);
        // 2.通过全类名获取 ( 最常用)
        // (注意:  1. 根据类型获取Bea时,要求IOC容器中有且只有一个类型匹配的bean, 如果有多个会 抛异常 NoUniqueBeanDefinitionException
        //        2. 若一个都没有 , 抛异常: NoSuchBeanDefinitionException
        Student bean2 = ioc.getBean(Student.class);
        System.out.println(bean2);

        //3 .根据bean 的 id 和 类型来获取
        Student bean3 = ioc.getBean("studentOne",Student.class);
        System.out.println(bean3);

    }
}

拓展 :

如果组件类实现了接口,根据接口类型可以获取 bean 吗?

可以,前提是bean唯一 如果一个接口有多个实现类,这些实现类都配置了 bean,

根据接口类型可以获取 bean 吗?

不行,因为bean不唯一,spring 不知道已改获取哪一个

结论:

根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类 型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。

即:

可以通过bean的类型, bean所继承的类的类型,bean所实现的接口的类型都可以获取bean

2.1.4 setter注入

为获取的bean对象赋值

  <bean id="studentTwe" class="com.ykh.spring.bean.Student">
        <!-- property标签:通过组件类的setXxx()方法给组件对象设置属性 -->
        <!-- name属性:指定属性名(这个属性名是getXxx()、setXxx()方法定义的,和成员变量无关)-->
        <!-- value属性:指定属性值 -->
        <property name="id" value="1001"/>
        <property name="name" value="张三"/>
        <property name="age" value="23"/>
        <property name="sex" value=""/>
    </bean>
2.1.5 构造器注入
<bean id="studentTwo" class="com.atguigu.spring.bean.Student">
<constructor-arg value="1002"></constructor-arg>
<constructor-arg value="李四"></constructor-arg>
<constructor-arg value="33"></constructor-arg>
<constructor-arg value=""></constructor-arg>
</bean>

注意:

constructor-arg标签还有两个属性可以进一步描述构造器参数:

index属性:指定参数所在位置的索引(从0开始)

name属性:指定参数名

2.1.6特殊字符的处理

①字面量赋值 什么是字面量?

int a = 10;

声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。

当我们引用a 的时候,我们实际上拿到的值是10。

而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,

这就是字面 量。所以字面量没有引申含义,就是我们看到的这个数据本身。

②null值

<property name="name">
<null />
</property>

注意:

<property name="name" value="null"></property>

以上写法,为name所赋的值是字符串nul

③xml实体

<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<property name="expression" value="a &lt; b"/>

④CDATA节

<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property>

2.3各种类型的数值注入

2.3.1 引用类型注入

方式一:引用外部已声明的bean 配置Clazz类型的bean:

<bean id="clazzOne" class="com.atguigu.spring.bean.Clazz">
<property name="clazzId" value="1111"></property>
<property name="clazzName" value="财源滚滚班"></property>
</bean>

为Student中的clazz属性赋值:


<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value=""></property>
<!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
<property name="clazz" ref="clazzOne"></property>
</bean>

方式二:内部bean

<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value=""></property>
<property name="clazz">
<!-- 在一个bean中再声明一个bean就是内部bean -->
<!-- 内部bean只能用于给属性赋值,不能在外部通过IOC容器获取,因此可以省略id属性 -->
<bean id="clazzInner" class="com.atguigu.spring.bean.Clazz">
<property name="clazzId" value="2222"></property>
<property name="clazzName" value="远大前程班"></property>
</bean>
</property>
</bean>

方式三:级联属性赋值

<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value=""></property>
<!-- 一定先引用某个bean为属性赋值,才可以使用级联方式更新属性 -->
<property name="clazz" ref="clazzOne"></property>
<property name="clazz.clazzId" value="3333"></property>
<property name="clazz.clazzName" value="最强王者班"></property>
</bean>

2.3.2 数组类型数值注入

在Student类中添加以下代码:

private String[] hobbies;
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}

配置bean

<bean id="studentFour" class="com.atguigu.spring.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="赵六"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
    <property name="clazz" ref="clazzOne"></property>
    <property name="hobbies">
         <array>
            <value>抽烟</value>
            <value>喝酒</value>
            <value>烫头</value>
         </array>
    </property>
</bean>
2.3.4 集合类型的注入

创建一个老师类 , 设置好构造方法和get\set方法,重写toString

public class Teacher {
    private Integer tid;
    private String teacherName;

    public Teacher() {
    }

    public Teacher(Integer tid, String teacherName) {
        this.tid = tid;
        this.teacherName = teacherName;
    }

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "tid=" + tid +
                ", teacherName='" + teacherName + '\'' +
                '}';
    }
}

在学生表中加入 老师的属性, 重写toString 方法和重新生成构造器

   private Map<String,Teacher> teacherMap;

    public Map<String, Teacher> getTeacherMap() {
        return teacherMap;
    }
    
    public void setTeacherMap(Map<String, Teacher> teacherMap) {
        this.teacherMap = teacherMap;
    }

配置bean,为teacherMao 进行注入( 赋值)

 <bean id="studentTwo" class="com.ykh.spring.pojo.Student">
        <property name="sid" value="10"/>
        <property name="sname" value="马超"/>
        <property name="age" value="12"/>
        <property name="gender" value=""/>
<!--        <property name="clazz" ref="clazzOne"/>-->
        <property name="hobby">
            <array>
                <value>抽烟</value>
                <value>喝酒</value>
                <value>烫头</value>
            </array>
        </property>
     <!--在此处为 teacherMap进行注入,使用map entry标签-->
        <property name="teacherMap">
            <map>
                <entry key="英语" value-ref="TeacherOne"/> <!--引用类型+上ref,引入外部的bean-->
                <entry key="数学" value-ref="TeacherTwo"/>
            </map>
        </property>
    </bean>
<!--配置老师的bean-->
    <bean id="TeacherOne" class="com.ykh.spring.pojo.Teacher">
        <property name="tid" value="10086"/>
        <property name="teacherName" value="英语老师"/>
    </bean>

    <bean id="TeacherTwo" class="com.ykh.spring.pojo.Teacher">
        <property name="tid" value="10010"/>
        <property name="teacherName" value="数学老师"/>
    </bean>
2.3.4 P命名空间

引入p命名空间后,可以通过以下方式为bean的各个属性赋值

<bean id="studentSix" class="com.atguigu.spring.bean.Student"
p:id="1006" p:name="小明" p:clazz-ref="clazzOne" p:teacherMapref="teacherMap"></bean>
2.3.5 引入外部属性文件

①加入依赖

        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>

        <!-- 数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>


②创建外部属性文件

image-20220822123118991

jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.jdbc.Driver

③引入属性文件

<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

④配置bean

<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

⑤测试

@Test
public void testDataSource() throws SQLException {
ApplicationContext ac = new ClassPathXmlApplicationContext("springdatasource.xml");
DataSource dataSource = ac.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
2.3.6 bean的作用域

bean 创建的对象默认是单例的 , 可以通过修改bean中 scope 来改为多例

image-20220822133712868

2.3.7 bean的生命周期

①具体的生命周期过程

  • bean对象创建(调用无参构造器)
  • 给bean对象设置属性
  • bean对象初始化之前操作(由bean的后置处理器负责)
  • bean对象初始化(需在配置bean时指定初始化方法)
  • bean对象初始化之后操作(由bean的后置处理器负责)
  • bean对象就绪可以使用
  • bean对象销毁(需在配置bean时指定销毁方法)
  • IOC容器关闭

2.4 FactoryBean

①简介

FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个 FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是 getObject()方法的返回值。

通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都 屏蔽起来,只把最简洁的使用界面展示给我们。

将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。

FactoryBean是一个接口,需要创建一个类实现该接口其中有三个方法:

  • getobject():通过一个对象交给IoC容器管理

  • getobjectType():设置所提供对象的类型

  • issingleton():所提供的对象是否单例

    当把FactoryBean的实现类配置为bean时,会将当前类中getobject()所返回的对象交给IoC容器管璃

②创建类UserFactoryBean

public class UserFactoryBean implements FactoryBean<User> {
    @Override //该方法返回对象给IOC管理
    public User getObject() throws Exception {
    	return new User();  //返回的是user对象
    }
    @Override
    public Class<?> getObjectType() {
    	return User.class;
    }
}

③配置bean

<bean id="user" class="com.atguigu.bean.UserFactoryBean"></bean>

④测试

@Test
public void testUserFactoryBean(){
	//获取IOC容器
	ApplicationContext ac = new ClassPathXmlApplicationContext("springfactorybean.xml");
    User user = (User) ac.getBean("user");
    System.out.println(user);
}

2.5 基于xml的自动装配

自动装配: 根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类 型属性赋值

使用bytype 根据类型自动找到bean ,

使用bean标签的autowire属性设置自动装配效果 自动装配方式:byType

byType:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值 若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值 null 若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常 NoUniqueBeanDefinitionException

<bean id="userController"
class="com.atguigu.autowire.xml.controller.UserController" autowire="byType">
</bean>
<bean id="userService"
class="com.atguigu.autowire.xml.service.impl.UserServiceImpl" autowire="byType">
</bean>
<bean id="userDao" class="com.atguigu.autowire.xml.dao.impl.UserDaoImpl"></bean>

使用byname 根据id 自动找到bean

byName:将自动装配的属性的属性名,作为bean的id在IOC容器中匹配相对应的bean进行赋值

image-20220828100044006

2.6 基于注解管理bean

①注解

和 XML 配置文件一样,注解本身并不能执行,注解本身仅仅只是做一个标记,具体的功能是框架检测 到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。

本质上:所有一切的操作都是Java代码来完成的,XML和注解只是告诉框架中的Java代码如何执行。

②扫描

Spring 为了知道程序员在哪些地方标记了什么注解,就需要通过扫描的方式,来进行检测。然后根据注 解进行后续操作。

基于注解管理bean要放在 类上

image-20220823183355155

通过查看源码我们得知,@Controller、@Service、@Repository这三个注解只是在@Component注解 的基础上起了三个新的名字。

对于Spring使用IOC容器管理这些组件来说没有区别。所以**@Controller**、@Service@Repository这 三个注解只是给开发人员看的,让我们能够便于分辨组件的作用。 注意:虽然它们本质上一样,但是为了代码的可读性,为了程序结构严谨我们肯定不能随便胡乱标记。

③扫描组件

情况一:最基本的扫描方式

<context:component-scan base-package="com.atguigu">
</context:component-scan>

情况二:指定要排除的组件

<context:component-scan base-package="com.atguigu">
<!-- context:exclude-filter标签:指定排除规则 -->
<!--
type:设置排除或包含的依据
type="annotation",根据注解排除,expression中设置要排除的注解的全类名
type="assignable",根据类型排除,expression中设置要排除的类型的全类名
-->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<!--<context:exclude-filter type="assignable"
expression="com.atguigu.controller.UserController"/>-->
</context:component-scan>

情况三:仅扫描指定组件

<context:component-scan base-package="com.atguigu" use-default-filters="false">
<!-- context:include-filter标签:指定在原有扫描规则的基础上追加的规则 -->
<!-- use-default-filters属性:取值false表示关闭默认扫描规则 -->
<!-- 此时必须设置use-default-filters="false",因为默认规则即扫描指定包下所有类 -->
<!--
type:设置排除或包含的依据
type="annotation",根据注解排除,expression中设置要排除的注解的全类名
type="assignable",根据类型排除,expression中设置要排除的类型的全类名
-->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<!--<context:include-filter type="assignable"
expression="com.atguigu.controller.UserController"/>-->
</context:component-scan>

2.7 基于注解管理的自动装配

  1. @Autowired注解

    • 在成员变量上直接标记@Autowired注解即可完成自动装配,不需要提供setXxx()方法。以后在项 目中的正式用法就是这样。
    • @Autowired注解可以标记在构造器和set方法上
    • 默认是根据 bytype 装配 , 在bytype 无法匹配的情况下, 根据byname 进行匹配

    image-20220823190211279

首先根据所需要的组件类型到IOC容器中查找 能够找到唯一的bean:

  • ​ 直接执行装配 如果完全找不到匹配这个类型的bean:

  • ​ 装配失败 和所需类型匹配的bean不止一个

    • ​ 没有@Qualifier注解:根据@Autowired标记位置成员变量的变量名作为bean的id进行 匹配

      • 能够找到:执行装配

      • 找不到:装配失败

    • 使用@Qualifier注解:根据@Qualifier注解中指定的名称作为bean的id进行匹配

    • 能够找到:执行装配

    • 找不到:装配失败

2.3 、AOP

3.1 代理模式

模拟场景

声明计算器接口Calculator,包含加减乘除的抽象方法

public interface Calculator {
int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i, int j);
}

创建实现类

public class CalculatorPureImpl implements Calculator {
    @Override
    public int add(int i, int j) {
        int result = i + j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
	@Override
    public int sub(int i, int j) {
        int result = i - j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
    @Override
    public int mul(int i, int j) {
        int result = i * j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
    @Override
    public int div(int i, int j) {
        int result = i / j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
}

要想在计算过程的前后添加日志的输出功能,需要通过代理模式 :

3.1.1 代理模式的概念:

将目标放一个代理对象中, 要调用目标方法时,通过代理对象进行调用, 在代理对象中实现对目标方法的控制, 就可以在 目标方法前后添加一些额外的功能. 而不影响核心代码.

image-20220824080924038

3.1.2 静态代理模式实现 :
//代理类要和 目标类实现相同的接口
public class CalculatorStaticProxy implements Calculator {
    // 将被代理的目标对象声明为成员变量
    private Calculator target;
    public CalculatorStaticProxy(Calculator target) {
    	this.target = target;
    }
    @Override
    public int add(int i, int j) {
        // 附加功能由代理类中的代理方法来实现
        System.out.println("[日志] add 方法开始了,参数是:" + i + "," + j);
        // 通过目标对象来实现核心业务逻辑
        int addResult = target.add(i, j);
        System.out.println("[日志] add 方法结束了,结果是:" + addResult);
    }
}

静态代理确实实现了解耦,但是由于代码都写死了,完全不具备任何的灵活性。

就拿日志功能来 说,将来其他地方也需要附加日志,那还得再声明更多个静态代理类,那就产生了大量重复的代 码,日志功能还是分散的,没有统一管理。

提出进一步的需求:将日志功能集中到一个代理类中,将来有任何日志需求,都通过这一个代理 类来实现。这就需要使用动态代理技术了。

3.1.3 动态代理模式实现

image-20220824110235266

实现代码

//1.创建一个生成 动态代理类的工厂
public class PraxyFactory {
   //2. 创建目标方法的对象
    Object target;

    //3. 生成构造方法
    public PraxyFactory(Object target) {
        this.target = target;
    }

    /**4.生产获取代理对象的方法
     * a> 通过java.lang.reflect 包下的 Proxy.newProxyInstance() 方法生成 代理对象 ,
     * b> 方法中的三个参数 :
     *       ClassLoader loader :    加载动态生成的代理类的类加载器
     *       Class<?>[] interfaces : 代理的对象所实现的接口的数组
     *       InvocationHandler h) :   设置代理对象实现目标方法的过程, 既如何重写 实现接口中的抽象方法
     *
     */
    public Object getPraxy() {
        //1) 通过反射获得目标方法的类加载器
        ClassLoader classLoader = target.getClass().getClassLoader();
        //2) 获得代理对象所实现的接口的数组
        Class<?>[] interfaces = target.getClass().getInterfaces();
        //3) 重写实现的接口中的方法
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                /**
                 *  praxy : 代理的对象
                 *  method: 代理对象中需要重写的方法
                 *  args :  需要重写的方法中的参数
                 */
                Object result = null;
                try {
                    System.out.println("[动态代理][日志] "+method.getName()+"参数:"+ Arrays.toString(args));
                    //调用通过目标对象调用目标方法
                    result = method.invoke(target, args);
                    System.out.println("[动态代理][日志] "+method.getName()+",结果:"+ result);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("[动态代理][日志] "+method.getName()+",异常:"+ e);
                } finally {
                    System.out.println("[动态代理][日志] "+method.getName()+",运行结束:");
                }
                return result;
            }
        };
        //返回生成的 代理对象
        return Proxy.newProxyInstance(classLoader,interfaces,h);
    }
}
3.2 AOP概念及相关术语
3.3.1、概述

AOP(Aspect Oriented Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面 向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现在不修改源代码的情况 下给程序动态统一添加额外功能的一种技术。

3.3.2、相关术语

①横切关注点

从每个方法中抽取出来的同一类非核心业务(如 日志功能) 。在同一个项目中,我们可以使用多个横切关注点对相关方 法进行多个不同方面的增强。 这个概念不是语法层面天然存在的,而是根据附加功能的逻辑上的需要:有十个附加功能,就有十个横 切关注点。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HaFSNMvj-1662124070278)(C:\Users\YKH\AppData\Roaming\Typora\typora-user-images\image-20220824162328857.png)]

②通知

每一个横切关注点上要做的事情都需要写一个方法来实现,这样的方法就叫通知方法。

  • 前置通知:在被代理的目标方法前执行
  • 返回通知:在被代理的目标方法成功结束后执行(寿终正寝)
  • 异常通知:在被代理的目标方法异常结束后执行(死于非命)
  • 后置通知:在被代理的目标方法最终结束后执行(盖棺定论)
  • 环绕通知:使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所 有位置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ecRg6I2B-1662124070278)(C:\Users\YKH\AppData\Roaming\Typora\typora-user-images\image-20220824162438115.png)]

③切面类

封装通知方法的类。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Kw7irSpO-1662124070279)(C:\Users\YKH\AppData\Roaming\Typora\typora-user-images\image-20220824162502434.png)]

④目标

被代理的目标对象。

⑤代理

向目标对象应用通知之后创建的代理对象。

⑥连接点

这也是一个纯逻辑概念,不是语法定义的。 把方法排成一排,每一个横切位置看成x轴方向,把方法从上到下执行的顺序看成y轴,x轴和y轴的交叉 点就是连接点。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wJl8gtNv-1662124070279)(C:\Users\YKH\AppData\Roaming\Typora\typora-user-images\image-20220824162542744.png)]

⑦切入点

定位连接点的方式。 每个类的方法中都包含多个连接点,

所以连接点是类中客观存在的事物(从逻辑上来说)。 如果把连接点看作数据库中的记录,那么切入点就是查询记录的 SQL 语句。 Spring 的 AOP 技术可以**通过切入点定位到特定的连接点****。 切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条 件。

3.3.3、作用
  • 简化代码:把方法中固定位置的重复的代码抽取出来,让被抽取的方法更专注于自己的核心功能, 提高内聚性。
  • 代码增强:把特定的功能封装到切面类中,看哪里有需要,就往上套,被套用了切面逻辑的方法就 被切面给增强了。

3.4、基于注解的AOP

3.4.1、技术说明

image-20220824162737756

  • 动态代理(InvocationHandler)

    JDK原生的实现方式,需要被代理的目标类必须实现接口。因 为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。

  • cglib:

    通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。

  • AspectJ:

本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最 终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。

3.4.2、准备工作

①添加依赖

在IOC所需依赖基础上再加入下面依赖即可:

<!-- spring-aspects会帮我们传递过来aspectjweaver -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.3.1</version>
</dependency>

②准备被代理的目标资源

接口 (上面的Calculator 接口)

实现类:

@Component
public class CalculatorPureImpl implements Calculator {
    @Override
    public int add(int i, int j) {
        int result = i + j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
    @Override
    public int sub(int i, int j) {
        int result = i - j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
    @Override
    public int mul(int i, int j) {
        int result = i * j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
    @Override
    public int div(int i, int j) {
        int result = i / j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
}

③ 配置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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
	<!--开启扫描-->
    <context:component-scan base-package="com.ykh.spring.aop"/>
    <!--打开aop-->
    <aop:aspectj-autoproxy />
</beans>

④创建切面类

/**
 * 创建一个切面类的步骤 :
 * 1. 创建一个类, 用@Aspect 将其标识为切面类
 * 2. 在其中写 增强方法, 用@Beafore ,@After等进行注解
 * 3. 注解时 设置切入点表达式 ( 可先先使用 @Pointcut 进行重用)
 * 4. 每个参数中通过 JoinPoint对象获取连接点的相关信息
 */
@Component
@Aspect //将这个类标识为切面类
public class LoggerAop {
    //声明: 切入点的重用
    @Pointcut("execution(* com.ykh.spring.aop.*.*(..))")
    public void pointCut() {
    }

    //前置通知
    @Before("pointCut()")
    public void beforeNotice(JoinPoint joinPoint) {
        //获取连接点对应方法的签名
        Signature signature = joinPoint.getSignature();
        //获取连接点对应方法的参数
        Object[] args = joinPoint.getArgs();
        System.out.println("LoggerAop 前置通知" + signature + "参数" + Arrays.toString(args));
    }

    //后置通知
    @After("pointCut()")
    public void afterNotice(JoinPoint joinPoint) {
        //获取连接点对应方法的签名
        Signature signature = joinPoint.getSignature();
        //获取连接点对应方法的参数
        Object[] args = joinPoint.getArgs();
        System.out.println("LoggerAop 后置通知" + signature + "参数" + Arrays.toString(args));
    }

    //返回通知
    @AfterReturning(value = "pointCut()", returning = "result")
    public void returnNotice(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->返回通知,方法名:" + methodName + ",结果:" + result);
    }

    //抛出异常通知
    @AfterThrowing(value = "pointCut()", throwing = "ex")
    public void throwingExceptionNotice(JoinPoint joinPoint, Throwable ex) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->异常通知,方法名:" + methodName + ",异常:" + ex);
    }

    //环绕通知 , 返回值类型要和目标方法一致
    @Around(value = "pointCut()")
    public Object aroundNotice(ProceedingJoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        Object result = null;
        try {
            System.out.println("环绕通知-->目标对象方法执行之前");
            //目标方法的执行,目标方法的返回值一定要返回给外界调用者
            result = joinPoint.proceed();
            System.out.println("环绕通知-->目标对象方法返回值之后");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("环绕通知-->目标对象方法出现异常时");
        } finally {
            System.out.println("环绕通知-->目标对象方法执行完毕");
        }
        return result;
    }
}

⑤ 准备测试类

public class AopTest {
    @Test
    public void beforeAopTest() {
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aop.xml");
        //此处使用向上转型, 通过接口来获取代理类
        Calculator bean = ioc.getBean(Calculator.class); 
        int result = bean.add(1, 2);
        System.out.println(result);
    }
}
3.4.4 切面的优先级
//可以通过order直接改变 代理对象的优先级
@Component
@Aspect
@Order(1)
public class AopOrderTest {

    @Before("execution(* com.ykh.spring.aop.*.*(..))")
    public void beforeTest() {
        System.out.println("5555555555555555");
    }
}

4.1、基于注解的声明式事务

4.1.1、准备工作

①加入依赖

<dependencies>
        <!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.1</version>
        </dependency>
        <!-- Spring 持久化层支持jar包 -->
        <!-- Spring 在执行持久化层操作、与持久化层技术进行整合过程中,需要使用orm、jdbc、tx三个
        jar包 -->
        <!-- 导入 orm 包就可以通过 Maven 的依赖传递性把其他两个也导入 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.3.1</version>
        </dependency>
        <!-- Spring 测试相关 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.1</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!-- 数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>
 </dependencies>

②创建jdbc.properties

jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
jdbc.driver=com.mysql.cj.jdbc.Driver

③配置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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.ykh.spring"/>
    <!-- 导入外部属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!-- 配置数据源 -->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 配置 JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 装配数据源 -->
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>

    <!--
开启事务的注解驱动
通过注解@Transactional所标识的方法或标识的类中所有的方法,都会被事务管理器管理事务
-->
    <!-- transaction-manager属性的默认值是transactionManager,如果事务管理器bean的id正好就
    是这个默认值,则可以省略这个属性 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

④创建表

CREATE TABLE `t_book` (
`book_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`book_name` varchar(20) DEFAULT NULL COMMENT '图书名称',
`price` int(11) DEFAULT NULL COMMENT '价格',
`stock` int(10) unsigned DEFAULT NULL COMMENT '库存(无符号)',
PRIMARY KEY (`book_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `t_book`(`book_id`,`book_name`,`price`,`stock`) values (1,'斗破苍
穹',80,100),(2,'斗罗大陆',50,100);
CREATE TABLE `t_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(20) DEFAULT NULL COMMENT '用户名',
`balance` int(10) unsigned DEFAULT NULL COMMENT '余额(无符号)',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
insert into `t_user`(`user_id`,`username`,`balance`) values (1,'admin',50);

⑤创建组件

创建BookController:

@Controller
public class BookController {

    //自动装配
    @Autowired  
    private BookService bookService;

    //调用 Service层
    public void buyBook(Integer bookId, Integer userId){
        bookService.buyBook(bookId, userId);
    }
}

创建接口BookService:

public interface BookService {
	void buyBook(Integer bookId, Integer userId);
}

创建实现类BookServiceImpl:

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    @Transactional
    public void buyBook(Integer bookId, Integer userId) {
        //查询图书的价格
        Integer price = bookDao.getPriceByBookId(bookId);
        //更新图书的库存
        bookDao.updateStock(bookId);
        //更新用户的余额
        bookDao.updateBalance(userId, price);
    }
}

创建接口BookDao:

public interface BookDao {
    //根据书的ID 获取书的价格
    Integer getPriceByBookId(Integer bookId);

    //修改库存
    void updateStock(Integer bookId);

    //修改用户余额
    void updateBalance(Integer userId, Integer price);
}

创建实现类BookDaoImpl:

@Repository
public class BookDaoImpl implements BookDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public Integer getPriceByBookId(Integer bookId) {
        String sql = "select price from t_book where book_id = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, bookId);
    }
    @Override
    public void updateStock(Integer bookId) {
        String sql = "update t_book set stock = stock - 1 where book_id = ?";
        jdbcTemplate.update(sql, bookId);
    }
    @Override
    public void updateBalance(Integer userId, Integer price) {
        String sql = "update t_user set balance = balance - ? where user_id = ?";
        jdbcTemplate.update(sql, price, userId);
    }
}
4.1.2、测试无事务情况

①创建测试类

//指定当前测试类在spring的运行环境中执行,此时就可以通过注入的方式直接获取ioc容器中的bean
@RunWith(SpringJUnit4ClassRunner.class) 
//设置spring测试环境的配置文件
@ContextConfiguration("classpath:tx-annocation.xml")
public class TxByAnnotationTest {
        @Autowired
        private BookController bookController;
        @Test
        public void testBuyBook(){
            bookController.buyBook(1, 1);
        }
}

②模拟场景

用户购买图书,先查询图书的价格,再更新图书的库存和用户的余额

假设用户id为1的用户,购买id为1的图书 用户余额为50,而图书价格为80 购买图书之后,用户的余额为-30,数据库中余额字段设置了无符号,因此无法将-30插入到余额字段 此时执行sql语句会抛出SQLException

③观察结果

因为没有添加事务,图书的库存更新了,但是用户的余额没有更新 显然这样的结果是错误的,购买图书是一个完整的功能,更新库存和更新余额要么都成功要么都失败

在开启自动提交事务的情况下, 每一条sql语句都独占一个事务, 执行完后会自动提交

4.1.3 、 加入事务

①添加事务配置

在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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.ykh.spring"/>
    <!-- 导入外部属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!-- 配置数据源 -->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 配置 JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 装配数据源 -->
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>

    <!--
开启事务的注解驱动
通过注解@Transactional所标识的方法或标识的类中所有的方法,都会被事务管理器管理事务
-->
    <!-- transaction-manager属性的默认值是transactionManager,如果事务管理器bean的id正好就
    是这个默认值,则可以省略这个属性 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

注意:导入的名称空间需要 tx 结尾的那个。

image-20220826082144977

②添加事务注解

因为service层表示业务逻辑层,一个方法表示一个完成的功能,因此处理事务一般在service层处理 在BookServiceImpl的buybook()添加注解@Transactiona

③观察结果

由于使用了Spring的声明式事务,更新库存和更新余额都没有执行

4.3.4、@Transactional注解标识的位置

@Transactional标识在方法上,则只会影响该方法

@Transactional标识的类上,则会影响类中所有的方法

4.3.5、事务属性:只读

①介绍

对一个查询操作来说,如果我们把它设置成只读,就能够明确告诉数据库,这个操作不涉及写操作。这 样数据库就能够针对查询操作来进行优化。

②使用方式

@Transactional(readOnly = true)
public void buyBook(Integer bookId, Integer userId) {
    //查询图书的价格
    Integer price = bookDao.getPriceByBookId(bookId);
    //更新图书的库存
    bookDao.updateStock(bookId);
    //更新用户的余额
    bookDao.updateBalance(userId, price);
    //System.out.println(1/0);
}

③注意

对增删改操作设置只读会抛出下面异常:

Caused by: java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed

4.3.6、事务属性:超时

①介绍

事务在执行过程中,有可能因为遇到某些问题,导致程序卡住,从而长时间占用数据库资源。

而长时间 占用资源,大概率是因为程序运行出现了问题(可能是Java程序或MySQL数据库或网络连接等等)。

此时这个很可能出问题的程序应该被回滚,撤销它已做的操作,事务结束,把资源让出来,让其他正常 程序可以执行。

概括来说就是一句话:超时回滚,释放资源。

②使用方式

@Transactional(timeout = 3)
public void buyBook(Integer bookId, Integer userId) {
    try {
   		 TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
    	e.printStackTrace();
    }
    //查询图书的价格
    Integer price = bookDao.getPriceByBookId(bookId);
    //更新图书的库存
    bookDao.updateStock(bookId);
    //更新用户的余额
    bookDao.updateBalance(userId, price);
    //System.out.println(1/0);
}

③观察结果

执行过程中抛出异常:

org.springframework.transaction.TransactionTimedOutException: Transaction timed out: deadline was Fri Jun 04 16:25:39 CST 2022

4.3.7、事务属性:回滚策略

①介绍

声明式事务默认只针对运行时异常回滚,编译时异常不回滚。

可以通过@Transactional中相关属性设置回滚策略

  • rollbackFor属性:需要设置一个Class类型的对象
  • rollbackForClassName属性:需要设置一个字符串类型的全类名
  • noRollbackFor属性:需要设置一个Class类型的对象
  • rollbackFor属性:需要设置一个字符串类型的全类名

使用方式

@Transactional(noRollbackFor = ArithmeticException.class)
//@Transactional(noRollbackForClassName = "java.lang.ArithmeticException")
public void buyBook(Integer bookId, Integer userId) {
    //查询图书的价格
    Integer price = bookDao.getPriceByBookId(bookId);
    //更新图书的库存
    bookDao.updateStock(bookId);
    //更新用户的余额
    bookDao.updateBalance(userId, price);
    System.out.println(1/0);
}

观察结果

虽然购买图书功能中出现了数学运算异常(ArithmeticException),但是我们设置的回滚策略是,当 出现ArithmeticException不发生回滚,因此购买图书的操作正常执行

4.3.8、事务属性:事务隔离级别

①介绍

数据库系统必须具有隔离并发运行各个事务的能力,使它们不会相互影响,避免各种并发问题。一个事 务与其他事务隔离的程度称为隔离级别。SQL标准中规定了多种事务隔离级别,不同隔离级别对应不同 的干扰程度,隔离级别越高,数据一致性就越好,但并发性越弱。

  • 隔离级别一共有四种:

​ 读未提交:READ UNCOMMITTED

  • 允许Transaction01读取Transaction02未提交的修改。

​ 读已提交:READ COMMITTED、

	要求Transaction01只能读取Transaction02已提交的修改。 
  • 可重复读:REPEATABLE READ

    确保Transaction01可以多次从一个字段中读取到相同的值,即Transaction01执行期间禁止其它 事务对这个字段进行更新。

  • 串行化:SERIALIZABLE

    确保Transaction01可以多次从一个表中读取到相同的行,在Transaction01执行期间,禁止其它 事务对这个表进行添加、更新、删除操作。可以避免任何并发问题,但性能十分低下。

各个隔离级别解决并发问题的能力见下表:

image-20220826083130727

各种数据库产品对事务隔离级别的支持程度:

image-20220826083147080

②使用方式

@Transactional(isolation = Isolation.DEFAULT)//使用数据库默认的隔离级别
@Transactional(isolation = Isolation.READ_UNCOMMITTED)//读未提交
@Transactional(isolation = Isolation.READ_COMMITTED)//读已提交
@Transactional(isolation = Isolation.REPEATABLE_READ)//可重复读
@Transactional(isolation = Isolation.SERIALIZABLE)//串行化
4.3.9、事务属性:事务传播行为

①介绍

当事务方法被另一个事务方法调用时,必须指定事务应该如何传播。例如:方法可能继续在现有事务中 运行,也可能开启一个新事务,并在自己的事务中运行。

测试

创建接口CheckoutService:

public interface CheckoutService {
	void checkout(Integer[] bookIds, Integer userId);
}

创建实现类CheckoutServiceImpl:

@Service
public class CheckoutServiceImpl implements CheckoutService {
    @Autowired
    private BookService bookService;
    @Override
    @Transactional
    //一次购买多本图书
    public void checkout(Integer[] bookIds, Integer userId) {
        for (Integer bookId : bookIds) {
        	bookService.buyBook(bookId, userId);
    	}
    }
}

在BookController中添加方法:

@Autowired
private CheckoutService checkoutService;
public void checkout(Integer[] bookIds, Integer userId){
    checkoutService.checkout(bookIds, userId);
}

在数据库中将用户的余额修改为100元

观察结果

可以通过@Transactional中的propagation属性设置事务传播行为

修改BookServiceImpl中buyBook()上,注解@Transactional的propagation属性

@Transactional(propagation = Propagation.REQUIRED),默认情况,表示如果当前线程上有已经开 启的事务可用,那么就在这个事务中运行。

经过观察,购买图书的方法buyBook()在checkout()中被调 用,checkout()上有事务注解,因此在此事务中执行。所购买的两本图书的价格为80和50,而用户的余 额为100,因此在购买第二本图书时余额不足失败,导致整个checkout()回滚,即只要有一本书买不 了,就都买不了

@Transactional(propagation = Propagation.REQUIRES_NEW),表示不管当前线程上是否有已经开启 的事务,都要开启新事务。同样的场景,每次购买图书都是在buyBook()的事务中执行,因此第一本图 书购买成功,事务结束,第二本图书购买失败,只在第二次的buyBook()中回滚,购买第一本图书不受 影响,即能买几本就买几本

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值