1.Spring 介绍

1.1 Spring官网介绍

官网地址: 官网地址:https://spring.io/
Spring框架网址地址: https://spring.io/projects/spring-framework
在这里插入图片描述

1.2 Spring介绍

Spring 是最受欢迎的企业级 Java 应用程序开发框架,数以百万的来自世界各地的开发人员使用 Spring 框架来创建性能好、易于测试、可重用的代码。

Spring 框架是一个开源的 Java 平台,它最初是由 Rod Johnson 编写的,并且于 2003 年 6 月首次在 Apache 2.0 许可下发布。

Spring 是轻量级的框架,其基础版本只有 2 MB 左右的大小。

Spring 框架的核心特性是可以用于开发任何 Java 应用程序,但是在 Java EE 平台上构建 web 应用程序是需要扩展的。 Spring 框架的目标是使 J2EE 开发变得更容易使用,通过启用基于 POJO 编程模型来促进良好的编程实践。

1.3 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 来实现。

1.4 Spring Framework五大功能模块

功能模块 功能介绍
Core Container 核心容器,在 Spring 环境下使用任何功能都必须基于 IOC 容器。
AOP&Aspects 面向切面编程
Testing 提供了对 junit 或 TestNG 测试框架的整合。
Data Access/Integration 提供了对数据访问/集成的功能。
Spring MVC 提供了面向Web应用程序的集成功能。

2. IOC容器介绍

2.1 获取资源的传统方式

自己做饭:买菜、洗菜、择菜、改刀、炒菜,全过程参与,费时费力,必须清楚了解资源创建整个过程中的全部细节且熟练掌握。

在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效率。

2.2 IOC容器

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

点外卖:下单、等、吃,省时省力,不必关心资源创建过程的所有细节。

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

2.3 DI依赖注入

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

DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器的资源注入。相对于IOC而言,这种表述更直接。

所以结论是:IOC 就是一种反转控制的思想, 而 DI 是对 IOC 的一种具体实现。

2.4 IOC-DI调用示意图

在这里插入图片描述

3.Spring入门案例

3.1 添加jar包

	<dependencies>
        <!--引入context包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.6</version>
        </dependency>

        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

jar包文件自动依赖结构
在这里插入图片描述

3.2 创建User对象

public class User {

    public void hello(){
        System.out.println("你好Spring");
    }
}

3.3 创建Spring配置文件

spring:默认的文件名称为: applicationContext.xml
在这里插入图片描述

3.4 创建bean对象

<!--
    配置User所对应的bean,即将User的对象交给Spring的IOC容器管理
    通过bean标签配置IOC容器所管理的bean
    属性:
        id:设置bean的唯一标识
        class:设置bean所对应类型的全类名
-->
	<bean id="user" class="com.atguigu.bean.User"/>

3.5 创建测试类

3.5.1 注意事项

Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘helloworld’ defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.atguigu.spring.bean.HelloWorld]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.atguigu.spring.bean.HelloWorld.<init>()

3.5.2 根据Id获取对象

	@Test
    public void testUser(){
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) applicationContext.getBean("user");
        user.hello();
    }

3.5.3 根据类型获取对象

	@Test
    public void testUser(){
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = applicationContext.getBean(User.class);
        user.hello();
    }

3.5.4 根据ID和类型获取对象

	@Test
    public void testUser(){
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = applicationContext.getBean("user",User.class);
        user.hello();
    }

3.5.5 注意事项

当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个

当IOC容器中一共配置了两个:

 <bean id="user1" class="com.atguigu.bean.User"/>
 <bean id="user2" class="com.atguigu.bean.User"/>

根据类型获取时会抛出异常:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘com.atguigu.bean.User’ available: expected single matching bean but found 2: user1,user2

3.6 知识扩展

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

可以,前提是bean唯一

如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?

不行,因为bean不唯一

3.7 结论

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

3.8 IOC容器在Spring中的实现

Spring 的 IOC 容器就是 IOC 思想的一个落地的产品实现。IOC 容器中管理的组件也叫做 bean。在创建 bean 之前,首先需要创建 IOC 容器。Spring 提供了 IOC 容器的两种实现方式:

3.8.1 BeanFactory

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

3.8.2 ApplicationContext

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

3.8.3 ApplicationContext的主要实现类

在这里插入图片描述

类型名 简介
ClassPathXmlApplicationContext 通过读取类路径下的 XML 格式的配置文件创建 IOC 容器对象
FileSystemXmlApplicationContext 通过文件系统路径读取 XML 格式的配置文件创建 IOC 容器对象
ConfigurableApplicationContext ApplicationContext 的子接口,包含一些扩展方法 refresh() 和 close() ,让 ApplicationContext 具有启动、关闭和刷新上下文的能力。
WebApplicationContext 专门为 Web 应用准备,基于 Web 环境创建 IOC 容器对象,并将对象引入存入 ServletContext 域中。

4. 依赖注入DI实现

4.1 Set注入

4.1.1 准备Bean对象

/**
 * @author 刘昱江
 * @className User
 * @description TODO
 * @date 2022/9/26 23:43
 */
public class User {

    private Integer id;
    private String name;

    public User() {

    }

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

4.1.2 通过配置文件为User对象赋值

<?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">
	 <!-- property标签:通过组件类的setXxx()方法给组件对象设置属性 -->
   	 <!-- name属性:指定属性名(这个属性名是getXxx()、setXxx()方法定义的,和成员变量无关) -->
     <!-- value属性:指定属性值 -->	
      <bean id="user" class="com.atguigu.bean.User">
            <property name="id" value="100"/>
            <property name="name" value="你好Spring"/>
      </bean>
</beans>

4.1.3 编辑测试方法

	@Test
    public void testUser(){
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = applicationContext.getBean(User.class);
        System.out.println(user);
    }

4.2 构造器注入

4.2.1 编辑实体类

public class User {

    private Integer id;
    private String name;
}

4.2.2 编辑配置文件

<!--
            index=0 表示参数下标
            name="xx" 参数形参名称
            value=""  构造注入赋值操作
      -->
      <bean id="user2" class="com.atguigu.bean.User">
            <constructor-arg index="0" value="100" name="id"/>
            <constructor-arg index="1" value="李四" name="name"/>
      </bean>

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

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

4.2.2 编辑测试类

@Test
    public void testUser2(){
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = applicationContext.getBean("user2",User.class);
        System.out.println(user);
    }

4.3 特殊值处理

4.3.1 字面量赋值

什么是字面量?
int a = 10;
声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。当我们引用a的时候,我们实际上拿到的值是10。
而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面量。所以字面量没有引申含义,就是我们看到的这个数据本身。

说明: 通过value属性为字面量赋值

<bean id="user1" class="com.atguigu.bean.User">
            <property name="id" value="100"/>
            <property name="name" value="你好Spring"/>
</bean>

4.3.2 赋值为NUll

 <bean id="user3" class="com.atguigu.bean.User">
            <constructor-arg  value="100" name="id"/>
            <!--这样的方式赋值表示 赋值null 字符串-->
            <!--<constructor-arg  value="null" name="name"/>-->
            <!--赋值null-->
            <constructor-arg name="name" >
                  <null/>
            </constructor-arg>
      </bean>

注意事项: value=“null” 表示其中的数据信息为null字符串

4.3.3 xml字符实体

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

说明: 使用万能的转义标签实现
IDEA快捷键: CD - > 回车

<property name="name">
     <value> <![CDATA[ <张三> ]]></value>
</property>

4.4 为类类型属性赋值

4.4.1 封装实体对象Dog

package com.atguigu.bean;

/**
 * @author 刘昱江
 * @className Dog
 * @description TODO
 * @date 2022/9/27 19:03
 */
public class Dog {
    private Integer id;
    private String name;

    public Dog(){

    }

    public Dog(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

4.4.2 封装实体对象User

package com.atguigu.bean;

/**
 * @author 刘昱江
 * @className User
 * @description TODO
 * @date 2022/9/26 23:43
 */
public class User {

    private Integer id;
    private String name;
    private Dog dog;  //宠物狗

    public User() {

    }

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", dog=" + dog +
                '}';
    }
}

4.4.3 外部bean引入

4.4.3.1 编辑xml配置文件
 	  <bean id="dog" class="com.atguigu.bean.Dog">
            <property name="id" value="101"/>
            <property name="name" value="哈士奇"/>
      </bean>

      <bean id="user5" class="com.atguigu.bean.User">
            <property name="id" value="100"/>
            <property name="name" value="张三"/>
            <!--使用关键字ref进行对象引入  不能使用value-->
            <property name="dog" ref="dog"/>
      </bean>
4.4.3.2 编辑测试类
//测试类型引用--外部bean引用
    @Test
    public void testUser5(){
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = applicationContext.getBean("user4",User.class);
        System.out.println(user.getName().toString());
    }

4.4.4 级联引入

说明: 首先定义空对象,之后通过对象.属性的方式 为数据赋值

	  <bean id="dog2" class="com.atguigu.bean.Dog"/>
      <bean id="user5" class="com.atguigu.bean.User">
            <property name="id" value="100"/>
            <property name="name" value="张三"/>

            <!--使用级联方式,必须保证对象有值 不能为null-->
            <property name="dog" ref="dog2"/>
            <property name="dog.id" value="101" />
            <property name="dog.name" value="阿拉斯加" />
      </bean>

4.4.5 内部bean引用方式

如果使用内部bean定义对象,则Dog对象不能被Spring的其它对象进行引用

	<bean id="user5" class="com.atguigu.bean.User">
            <property name="id" value="100"/>
            <property name="name" value="张三"/>
            <property name="dog">
                  <bean id="dog" class="com.atguigu.bean.Dog">
                        <property name="id" value="1002"/>
                        <property name="name" value="萨摩耶"/>
                  </bean>
            </property>
      </bean>

4.5 为数组数据类型赋值

4.5.1 修改实体对象

说明: 在实体对象中添加数组结构, 之后手动添加get/set方法

 	private Integer id;
    private String name;
    private Dog dog;  //宠物狗
    private String[] hobby;

4.5.2 编辑xml配置文件

说明: 其中array是关键字, 如果是字面量则可以编辑value ,如果是类型则需要通过ref引用

<!--为数组类型赋值-->
      <bean id="user6" class="com.atguigu.bean.User">
            <property name="id" value="100"/>
            <property name="name" value="张三"/>
            <property name="hobby">
                  <array>
                        <value>敲代码</value>
                        <value>打游戏</value>
                        <value>看电影</value>
                  </array>
            </property>
      </bean>

4.6 为集合类型赋值

4.6.1 添加List集合属性

说明: 添加list集合属性,之后添加get/set方法 并且添加toString的方法

private List list;  //定义list集合

4.6.2 为List集合类型赋值

4.6.2.1 通过内部引入为List集合赋值
<bean id="user" class="com.atguigu.bean.User">
            <property name="id" value="1001"/>
            <property name="name" value="光明正大"/>
            <property name="list">
                  <list>
                        <value>好吃的</value>
                        <value>好喝的</value>
                        <value>好玩的</value>
                  </list>
            </property>
      </bean>
4.6.2.2 使用util标签引入List集合

说明: 如果list集合需要被其它标签引入,则使用util标签进行定义
引入标签: <util:list> 之后会有自动提示 自动导入即可

	  <bean id="user1" class="com.atguigu.bean.User">
            <property name="id" value="1001"/>
            <property name="name" value="光明正大"/>
            <property name="list" ref="list"></property>
      </bean>

     <util:list id="list">
           <value>好吃的</value>
           <value>好喝的</value>
           <value>好玩的</value>
     </util:list>

4.6.3 为Set集合类型赋值

说明: 为Set集合赋值的操作和List集合操作相同.

		<bean id="user1" class="com.atguigu.bean.User">
            <property name="id" value="1001"/>
            <property name="name" value="光明正大"/>
            <property name="list" ref="list"></property>
            <property name="set" ref="set">
                <!--<set>
                    <value>100</value>
                    <value>200</value>
                    <value>300</value>
                </set>-->
            </property>
      </bean>

     <util:list id="list">
           <value>好吃的</value>
           <value>好喝的</value>
           <value>好玩的</value>
     </util:list>

     <util:set id="set">
         <value>333</value>
         <value>444</value>
         <value>555</value>
     </util:set>

4.6.4 为Map集合类型赋值

4.6.4.1 添加Map属性
	private Map map;    //定义Map集合

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }
4.6.4.2 编辑配置文件
		<bean id="user1" class="com.atguigu.bean.User">
            <property name="id" value="1001"/>
            <property name="name" value="光明正大"/>
            <property name="list" ref="list"></property>
            <property name="set" ref="set"/>
            <property name="map" ref="map">
                <!--<map>
                    <entry key="a" value="100"></entry>
                    <entry key="b" value="200"></entry>
                    <entry key="c" value="300"></entry>
                </map>-->
            </property>
      </bean>
      
      <util:map id="map">
        <entry key="a" value="100"></entry>
        <entry key="b" value="200"></entry>
        <entry key="c" value="300"></entry>
      </util:map>

4.6.5 P命名空间

说明: 引入P标签
快捷键: p: 之后通过IDEA自动引入
使用方式: P中有2种用法 带ref表示对象的引用, 不带ref表示直接量赋值

	<?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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="user1" class="com.atguigu.bean.User" p:id="100" p:name="张三" p:list-ref="list"/>

    <util:list id="list">
        <value>11</value>
        <value>22</value>
        <value>33</value>
    </util:list>

</beans>

4.7 Spring引入外部配置文件

4.7.1 业务说明

Spring通过IOC机制可以管理 其它对象, 如果需要整合Mybatis则必须管理数据源. 那么Spring应该如何管理数据源?

4.7.2 添加jar包文件

<!-- 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>

4.7.3 创建jdbc.properties文件

说明: 在项目的根目录 添加配置文件 jdbc.properties

	jdbc.driver=com.mysql.cj.jdbc.Driver
	jdbc.url=jdbc:mysql://localhost:3306/atweb?serverTimezone=UTC
	jdbc.username=root
	jdbc.password=root

4.7.4 引入外部配置文件

	<!--引入指定配置文件-->
	<context:property-placeholder location="jdbc.properties"/>

4.7.5 创建数据源对象

	<bean id="dataSource" 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>

4.7.6 添加测试类

	@Test
    public void testUser() throws SQLException {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        DruidDataSource dataSource = applicationContext.getBean(DruidDataSource.class);
        System.out.println(dataSource.getConnection());
    }

4.8 Bean的作用域

4.8.1 bean作用域概念

在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:

取值 含义 创建对象的时机
singleton(默认) 在IOC容器中,这个bean的对象始终为单实例 IOC容器初始化时
prototype 这个bean在IOC容器中有多个实例 获取bean时

如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):

取值 含义
request 在一个请求范围内有效
session 在一个会话范围内有效

4.8.2 编辑xml配置文件

	<!--
        scope="singleton" 默认单例  spring容器创建时对象创建
        scope="prototype" 设置为多例对象  当容器getBean时 获取对象信息
    -->
    <bean id="user1" class="com.atguigu.bean.User" scope="prototype"></bean>

4.8.3 编辑测试类

	@Test
    public void testUser() throws SQLException {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User bean1 = applicationContext.getBean(User.class);
        User bean2 = applicationContext.getBean(User.class);
        System.out.println(bean1 == bean2);
    }

4.9 Bean的生命周期

4.9.1 Bean的生命周期

  • bean对象创建(调用无参构造器)

  • 给bean对象设置属性

  • bean的后置处理器(初始化之前)

  • bean对象初始化(需在配置bean时指定初始化方法)

  • bean的后置处理器(初始化之后)

  • bean对象就绪可以使用

  • bean对象销毁(需在配置bean时指定销毁方法)

  • IOC容器关闭

4.9.2 编辑User类

package com.atguigu.bean;


/**
 * @author 刘昱江
 * @className User
 * @description TODO
 * @date 2022/9/26 23:43
 */
public class User {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        System.out.println("2-依赖注入");
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public User(){
        System.out.println("1-创建对象");
    }

    public void init(){
        System.out.println("3-调用初始化方法");
    }

    public void hello(){
        System.out.println("4-业务调用方法");
    }

    public void destroy(){
        System.out.println("5-对象销毁方法");
    }
}

4.9.3 编辑测试类

	@Test
    public void testUser2() throws SQLException {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User user2 = applicationContext.getBean("user2",User.class);
        user2.hello();
        applicationContext.close();
    }

4.9.4 编辑测试类

在这里插入图片描述

4.9.5 Bean的后置处理器

bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,
需要注意的是: bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行

/**
 * @author 刘昱江
 * @className MyBeanPostProcess
 * @description TODO
 * @date 2022/9/28 11:02
 */
public class MyBeanPostProcess implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("初始化方法前调用!!"+ beanName);
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("初始化方法后调用!!"+beanName);
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}

4.9.6 Bean后置处理器配置

	<!--定义初始化处理器-->
	<bean id="myBeanPostProcess" class="com.atguigu.process.MyBeanPostProcess"></bean>

4.10 FactoryBean接口

4.10.1 FactoryBean简介

FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。

4.10.2 Factory Bean介绍

public interface FactoryBean<T> {
	String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
	@Nullable
	T getObject() throws Exception;

	@Nullable
	Class<?> getObjectType();

	default boolean isSingleton() {
		return true;
	}
}

4.10.3 利用FactoryBean创建User对象

package com.atguigu.factory;

import com.atguigu.bean.User;
import org.springframework.beans.factory.FactoryBean;

/**
 * @author 刘昱江
 * @className UserFactory
 * @description TODO
 * @date 2022/9/28 11:25
 */
public class UserFactory implements FactoryBean<User> {

    @Override
    public User getObject() throws Exception {
        return new User();
    }

    @Override
    public Class<?> getObjectType() {
        return User.class;
    }
}

4.10.4 编辑配置文件

<!--工厂模式创建对象-->
<bean id="user3" class="com.atguigu.factory.UserFactory"/>

4.10.5 代码测试

	@Test
    public void testUser3() throws SQLException {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = applicationContext.getBean("user3",User.class);
        user.hello();
        System.out.println("结果输出!");
        applicationContext.close();
    }

5 Spring自动装配

5.1 自动装配

5.1.1 什么是自动装配

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

5.1.2 IOC 实现层级代码搭建

层级代码结构: Controller Service Dao

创建类UserController

public class UserController {

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void saveUser(){
        userService.saveUser();
    }

}

创建接口UserService

public interface UserService {

    void saveUser();

}

创建类UserServiceImpl实现接口UserService

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void saveUser() {
        userDao.saveUser();
    }

}

创建接口UserDao

public interface UserDao {

    void saveUser();

}

创建类UserDaoImpl实现接口UserDao

public class UserDaoImpl implements UserDao {

    @Override
    public void saveUser() {
        System.out.println("保存成功");
    }

}

5.2 ByType 自动装配

5.2.1 自动装配说明

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

5.2.2 编辑配置文件

	<!--自动装配类型 调用set方法为属性赋值
        autowire="default"  autowire="no" 表示不会自动装配 以默认值为准
        autowire="byType"   根据类型自动装配
    -->
    <bean id="userController" class="com.atguigu.controller.UserController" autowire="byType"/>
    <bean id="userService" class="com.atguigu.service.UserServiceImpl" autowire="byType"/>
    <bean id="userDao" class="com.atguigu.dao.UserDaoImpl"/>

5.3 ByName 自动装配

5.3.1 根据名称自动装配

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

注意事项:
一般条件下 默认使用byType 根据类型匹配.
如果配置文件中有同类型的Bean 则可以使用byName进行区分

5.3.2 编辑配置文件

	<bean id="userController" class="com.atguigu.controller.UserController" autowire="byName"/>
    <bean id="userService11" class="com.atguigu.service.UserServiceImpl" autowire="byName"/>
    <bean id="userDao11" class="com.atguigu.dao.UserDaoImpl"/>

5.4 基于注解管理bean

5.4.1 关于注解介绍

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

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

举例:元旦联欢会要布置教室,蓝色的地方贴上元旦快乐四个字,红色的地方贴上拉花,黄色的地方贴上气球。

在这里插入图片描述
班长做了所有标记,同学们来完成具体工作。墙上的标记相当于我们在代码中使用的注解,后面同学们做的工作,相当于框架的具体操作。

5.4.2 常用注解

@Component:将类标识为普通组件
@Controller:将类标识为控制层组件
@Service:将类标识为业务层组件
@Repository:将类标识为持久层组件

注解之间的关系;

在这里插入图片描述

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

对于Spring使用IOC容器管理这些组件来说没有区别。所以@Controller、@Service、@Repository这三个注解只是给开发人员看的,让我们能够便于分辨组件的作用。

注意:虽然它们本质上一样,但是为了代码的可读性,为了程序结构严谨我们肯定不能随便胡乱标记。

5.4.3 组件扫描方式

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

5.4.3.1 基本扫描方式
	 <!--指定包扫描路径 会扫描其子孙包数据...-->
     <context:component-scan base-package="com.atguigu"/>

测试类:

	@Test
    public void testUser() throws SQLException {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = applicationContext.getBean(UserController.class);
        UserService userService = applicationContext.getBean(UserService.class);
        UserDao userDao = applicationContext.getBean(UserDao.class);
        System.out.println(userController);
        System.out.println(userService);
        System.out.println(userDao);
    }
5.4.3.2 排除指定的组件

在SpringMVC中可能只扫描Controller层, 而Spring框架负责扫描 Service/Dao层 如何才能解决重复扫描的问题呢?

	<!--指定包扫描路径-->
     <context:component-scan base-package="com.atguigu">
          <!--
               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.service.UserServiceImpl"/>

     </context:component-scan>

在这里插入图片描述

5.4.3.3 加载指定的组件
	<!--指定包扫描路径
          use-default-filters="false" 默认包扫描失效
          use-default-filters="true"  开启默认包扫描
     -->
     <context:component-scan base-package="com.atguigu" use-default-filters="false">
          <!--
               type:设置排除或包含的依据
		       type="annotation",根据注解排除,expression中设置要排除的注解的全类名
		       type="assignable",根据类型排除,expression中设置要排除的类型的全类名
          -->
          <!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
          <context:exclude-filter type="aspectj" expression="com.atguigu.service.UserServiceImpl"/>-->
          <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
     </context:component-scan>

指定测试类

	@Test
    public void testUser() throws SQLException {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = applicationContext.getBean(UserController.class);
        //UserService userService = applicationContext.getBean(UserService.class);
        UserDao userDao = applicationContext.getBean(UserDao.class);
        System.out.println(userController);
        //System.out.println(userService);
        System.out.println(userDao);
    }

5.4.4 管理Bean的Id

在我们使用XML方式管理bean的时候,每个bean都有一个唯一标识,便于在其他地方引用。
现在使用注解后,每个组件仍然应该有一个唯一标识。

默认情况

类名首字母小写就是bean的id。例如:UserController类对应的bean的id就是userController。

自定义bean的id

可通过标识组件的注解的value属性设置自定义的bean的id

@Service(“userService”) //默认为userServiceImpl
public class UserServiceImpl implements UserService {}

5.5 基于注解的自动装配

5.5.1 代码基本结构

在UserController中声明UserService对象

在UserServiceImpl中声明UserDao对象

5.5.2 @Autowired注解

在成员变量上直接标记@Autowired注解即可完成自动装配,不需要提供setXxx()方法。以后我们在项目中的正式用法就是这样。

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    public void saveUser(){
        userService.saveUser();
    }

}
public interface UserService {
    void saveUser();
}
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void saveUser() {
        userDao.saveUser();
    }
}
public interface UserDao {
    void saveUser();
}
@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void saveUser() {
        System.out.println("保存成功");
    }
}

5.5.3 @Autowired 额外配置

说明: @Autowired注解可以标记在构造器和set方法上

@Controller
public class UserController {

    private UserService userService;
    
    @Autowired
    public UserController(UserService userService){
        this.userService = userService;
    }

    public void saveUser(){
        userService.saveUser();
    }

}
@Controller
public class UserController {

    private UserService userService;
    
    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    public void saveUser(){
        userService.saveUser();
    }

}

5.5.4 @Autowired工作流程

在这里插入图片描述
首先根据所需要的组件类型到IOC容器中查找

  • 首先根据类型匹配,如果找到直接注入找不到对象按照Id进行匹配
  • 如果按照Id能找到对象 则注入,找不到则报错.
  • 如果使用@Qualifier注解 则强制使用Id进行注入

5.5.5 @Qualifier注解说明

@Controller
public class UserController {
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    public void saveUser(){
        userService.saveUser();
    }
}

@Autowired中有属性required,默认值为true,因此在自动装配无法找到相应的bean时,会装配失败
可以将属性required的值设置为false,则表示能装就装,装不上就不装,
但是实际开发时,基本上所有需要装配组件的地方都是必须装配的,用不上这个属性。

6. 代理模式

6.1 场景模拟

6.1.1 接口声明

说明: 准备一个接口,其中包含了add/sub/mul/div等方法, 完成加/减/乘/除的操作

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);
}

6.1.2 创建实现类

在这里插入图片描述

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;
    }
}

6.1.3 创建带日志功能的实现类

在这里插入图片描述

public class CalculatorLogImpl implements Calculator {
    
    @Override
    public int add(int i, int j) {
    
        System.out.println("[日志] add 方法开始了,参数是:" + i + "," + j);
    
        int result = i + j;
    
        System.out.println("方法内部 result = " + result);
    
        System.out.println("[日志] add 方法结束了,结果是:" + result);
    
        return result;
    }
    
    @Override
    public int sub(int i, int j) {
    
        System.out.println("[日志] sub 方法开始了,参数是:" + i + "," + j);
    
        int result = i - j;
    
        System.out.println("方法内部 result = " + result);
    
        System.out.println("[日志] sub 方法结束了,结果是:" + result);
    
        return result;
    }
    
    @Override
    public int mul(int i, int j) {
    
        System.out.println("[日志] mul 方法开始了,参数是:" + i + "," + j);
    
        int result = i * j;
    
        System.out.println("方法内部 result = " + result);
    
        System.out.println("[日志] mul 方法结束了,结果是:" + result);
    
        return result;
    }
    
    @Override
    public int div(int i, int j) {
    
        System.out.println("[日志] div 方法开始了,参数是:" + i + "," + j);
    
        int result = i / j;
    
        System.out.println("方法内部 result = " + result);
    
        System.out.println("[日志] div 方法结束了,结果是:" + result);
    
        return result;
    }
}

6.1.4 提出问题

①现有代码缺陷

针对带日志功能的实现类,我们发现有如下缺陷:

  • 对核心业务功能有干扰,导致程序员在开发核心业务功能时分散了精力
  • 附加功能分散在各个业务功能方法中,不利于统一维护
②解决思路

解决这两个问题,核心就是:解耦。我们需要把附加功能从业务功能代码中抽取出来。

③困难

解决问题的困难:要抽取的代码在方法内部,靠以前把子类中的重复代码抽取到父类的方式没法解决。所以需要引入新的技术。

6.2 代理模式

6.2.1 代理模式介绍

①介绍

二十三种设计模式中的一种,属于结构型模式。它的作用就是通过提供一个代理类,让我们在调用目标方法的时候,不再是直接对目标方法进行调用,而是通过代理类间接调用。让不属于目标方法核心逻辑的代码从目标方法中剥离出来——解耦。调用目标方法时先调用代理对象的方法,减少对目标方法的调用和打扰,同时让附加功能能够集中在一起也有利于统一维护。
在这里插入图片描述
使用代理之后:
在这里插入图片描述

②生活中的代理
  • 广告商找大明星拍广告需要经过经纪人
  • 合作伙伴找大老板谈合作要约见面时间需要经过秘书
  • 房产中介是买卖双方的代理
③相关术语
  • 代理:将非核心逻辑剥离出来以后,封装这些非核心逻辑的类、对象、方法。
  • 目标:被代理“套用”了非核心逻辑代码的类、对象、方法。

6.3 静态代理机制

6.3.1 静态代理业务调用

在这里插入图片描述

6.3.2 静态代理实现

package com.atguigu;

/**
 * @author 刘昱江
 * @className CalculatorProxy
 * @description TODO
 * @date 2022/9/29 19:03
 */
public class CalculatorProxy implements Calculator{

    private Calculator target;

    public CalculatorProxy(Calculator target) {
        this.target = target;
    }

    @Override
    public int add(int i, int j) {
        System.out.println("[日志] add方式开始执行:  参数1:"+i+"~~"+ "参数2:"+j);
        int result = target.add(i,j);
        System.out.println("[日志] add方式结束执行:  结果是"+result);
        return result;
    }

    @Override
    public int sub(int i, int j) {
        System.out.println("[日志] sub方式开始执行:  参数1:"+i+"~~"+ "参数2:"+j);
        int result = target.sub(i,j);
        System.out.println("[日志] sub方式结束执行:  结果是"+result);
        return result;
    }

    @Override
    public int mul(int i, int j) {
        System.out.println("[日志] mul方式开始执行:  参数1:"+i+"~~"+ "参数2:"+j);
        int result = target.mul(i,j);
        System.out.println("[日志] mul方式结束执行:  结果是"+result);
        return result;
    }

    @Override
    public int div(int i, int j) {
        System.out.println("[日志] div方式开始执行:  参数1:"+1+"~~"+ "参数2:"+j);
        int result = target.div(i,j);
        System.out.println("[日志] div方式结束执行:  结果是"+result);
        return result;
    }
}

6.3.3 测试静态代理代码

 	@Test
    public void testUser() throws SQLException {
        CalculatorImpl target = new CalculatorImpl();
        Calculator calculator = new CalculatorProxy(target);
        int add = calculator.add(100, 100);
        int div = calculator.div(100, 10);
        System.out.println("求和结果:"+add);
        System.out.println("商的结果:"+div);
    }

6.4 动态代理机制

6.4.1 动态代理介绍

在这里插入图片描述

6.4.2 创建代理对象

package com.atguigu;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 刘昱江
 * @className DynamicProxy
 * @description TODO
 * @date 2022/10/2 22:06
 */
public class DynamicProxy {

    public static Object getProxy(Object target){

        /**
         * 参数介绍
         *  1.类加载器
         *  2.目标对象的接口
         *  3.业务执行回调函数InvocationHandler  handler对象
         */
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;
                        try {
                            System.out.println("[日志]"+method.getName()+"方式开始执行:  参数1:"+args[0]+"~~"+ "参数2:"+args[1]);
                            result = method.invoke(target,args);
                            System.out.println("[日志]"+method.getName()+"方式开始结束:  返回值:"+result);
                        }catch (Exception e){
                            System.out.println("[日志]"+method.getName()+"|异常信息:"+e.getMessage());
                        }finally {
                            System.out.println("[日志]动态代理执行完成: 返回值结果:"+result);
                        }
                        return result;
                    }
                });
    }
}

6.4.3 测试结果显示

在这里插入图片描述

6.5 Cglib动态代理

6.5.1 编辑代理类

public class CglibProxy {

    public static Object getProxy(Object target){

        //1.定义增强器对象
        Enhancer enhancer = new Enhancer();
        //2.为属性赋值
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try {
                    System.out.println("[日志]"+method.getName()+"方式开始执行:  参数1:"+objects[0]+"~~"+ "参数2:"+objects[1]);
                    result = method.invoke(target,objects);
                    System.out.println("[日志]"+method.getName()+"方式开始结束:  返回值:"+result);
                }catch (Exception e){
                    System.out.println("[日志]"+method.getName()+"|异常信息:"+e.getMessage());
                }finally {
                    System.out.println("[日志]动态代理执行完成: 返回值结果:"+result);
                }
                return result;
            }
        });

        return enhancer.create();
    }
}

6.5.2 编辑测试类

@Test
    public void testCglibProxy(){
        CalculatorImpl target = new CalculatorImpl();
        Calculator calculator = (Calculator) CglibProxy.getProxy(target);
        System.out.println(calculator.getClass());
        int add = calculator.add(100, 200);
        System.out.println("返回值结果:"+add);
    }

6.6 动态代理总结(重点)

  • 代理方式不同

JDK代理使用的是反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。
CGLIB代理使用字节码处理框架asm,对代理对象类的class文件加载进来,通过修改字节码生成子类。

  • 效率不同

JDK创建代理对象效率较高,执行效率较低;
CGLIB创建代理对象效率较低,执行效率高。

  • 生成方式不同

JDK动态代理机制是委托机制,只能对实现接口的类生成代理,通过反射动态实现接口类;
CGLIB则使用的继承机制,针对类实现代理,被代理类和代理类是继承关系,所以代理类是可以赋值给被代理类的,因为是继承机制,不能代理final修饰的类。

  • 是否需要第三方类库

JDK代理是不需要依赖第三方的库,只要JDK环境就可以进行代理,需要满足以下要求:
1.实现InvocationHandler接口,重写invoke()
2.使用Proxy.newProxyInstance()产生代理对象
3.被代理的对象必须要实现接口

CGLib 必须依赖于CGLib的类库,需要满足以下要求:
1.实现MethodInterceptor接口,重写intercept()
2.使用Enhancer对象.create()产生代理对象

7 AOP概念及相关术语

7.1 概述

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

7.2 相关术语

7.2.1 横切关注点

从每个方法中抽取出来的同一类非核心业务。在同一个项目中,我们可以使用多个横切关注点对相关方法进行多个不同方面的增强。

这个概念不是语法层面天然存在的,而是根据附加功能的逻辑上的需要:有十个附加功能,就有十个横切关注点。

在这里插入图片描述

7.2.2 通知

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

在这里插入图片描述

7.2.3 切面

封装通知方法的类。
在这里插入图片描述

7.2.4 目标对象

被代理的目标对象。

7.2.5 代理对象

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

7.2.6 连接点

这也是一个纯逻辑概念,不是语法定义的。

把方法排成一排,每一个横切位置看成x轴方向,把方法从上到下执行的顺序看成y轴,x轴和y轴的交叉点就是连接点。

7.2.7 切入点

定位连接点的方式。

每个类的方法中都包含多个连接点,所以连接点是类中客观存在的事物(从逻辑上来说)。

如果把连接点看作数据库中的记录,那么切入点就是查询记录的 SQL 语句。

Spring 的 AOP 技术可以通过切入点定位到特定的连接点。

切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。

7.3 AOP作用

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

7.4 基于注解的AOP

7.4.1 业务调用说明

在这里插入图片描述

7.4.2 添加jar包

		<!--引入context包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.6</version>
        </dependency>

7.4.3 定义接口

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);
    
}

7.4.4 编辑业务实现类

/**
 * @author 刘昱江
 * @className CalculatorImpl
 * @description TODO
 * @date 2022/10/2 23:10
 */
@Service
public class CalculatorImpl implements Calculator{

    @Override
    public int add(int i, int j) {
        return i+j;
    }

    @Override
    public int sub(int i, int j) {
        return i-j;
    }

    @Override
    public int mul(int i, int j) {
        return i*j;
    }

    @Override
    public int div(int i, int j) {
        return i/j;
    }
}

7.4.5 编辑切面类

// @Aspect表示这个类是一个切面类
@Aspect
// @Component注解保证这个切面类能够放入IOC容器
@Component
public class LogAspect {
    
    @Before("execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
    }

    @After("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->后置通知,方法名:"+methodName);
    }

    @AfterReturning(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->返回通知,方法名:"+methodName+",结果:"+result);
    }

    @AfterThrowing(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->异常通知,方法名:"+methodName+",异常:"+ex);
    }
    
    @Around("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
    public Object aroundMethod(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;
    }
    
}

7.4.6 编辑Spring配置文件

	<!--
        基于注解的AOP的实现:
        1、将目标对象和切面交给IOC容器管理(注解+扫描)
        2、开启AspectJ的自动代理,为目标对象自动生成代理
        3、将切面类通过注解@Aspect标识
    -->

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

    <aop:aspectj-autoproxy />

7.4.7 通知介绍

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

7.4.8 通知介绍

各种通知的执行顺序:

  • Spring版本5.3.x以前:
    • 前置通知
    • 目标操作
    • 后置通知
    • 返回通知或异常通知
  • Spring版本5.3.x以后:
    • 前置通知
    • 目标操作
    • 返回通知或异常通知
    • 后置通知

7.4.9 切入点表达式

  • 用*号代替“权限修饰符”和“返回值”部分表示“权限修饰符”和“返回值”不限

  • 在包名的部分,一个“*”号只能代表包的层次结构中的一层,表示这一层是任意的。

    • 例如:*.Hello匹配com.Hello,不匹配com.atguigu.Hello
  • 在包名的部分,使用“*…”表示包名任意、包的层次深度任意

  • 在类名的部分,类名部分整体用*号代替,表示类名任意

  • 在类名的部分,可以使用*号代替类名的一部分

    • 例如:*Service匹配所有名称以Service结尾的类或接口
  • 在方法名部分,可以使用*号表示方法名任意

  • 在方法名部分,可以使用*号代替方法名的一部分

    • 例如:*Operation匹配所有方法名以Operation结尾的方法
  • 在方法参数列表部分,使用(…)表示参数列表任意

  • 在方法参数列表部分,使用(int,…)表示参数列表以一个int类型的参数开头

  • 在方法参数列表部分,基本数据类型和对应的包装类型是不一样的

    • 切入点表达式中使用 int 和实际方法中 Integer 是不匹配的
  • 在方法返回值部分,如果想要明确指定一个返回值类型,那么必须同时写明权限修饰符

    • 例如:execution(public int *…Service.(…, int)) 正确
    • 例如:execution(* int *…Service.(…, int)) 错误

在这里插入图片描述

7.5 各个通知使用说明

7.5.1 定义切入点表达式

@Pointcut("execution(* com.atguigu.aop.annotation.*.*(..))")
public void pointCut(){}

7.5.2 引入公共切入点

@Before("pointCut()")
public void beforeMethod(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}

7.5.3 不同切面中引用

@Before("com.atguigu.aop.CommonPointCut.pointCut()")
public void beforeMethod(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}

7.5.4 获取通知的相关信息

7.5.4.1 获取连接点信息

获取连接点信息可以在通知方法的参数位置设置JoinPoint类型的形参

@Before("execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint){
    //获取连接点的签名信息
    String methodName = joinPoint.getSignature().getName();
    //获取目标方法到的实参信息
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}
7.5.4.2 获取目标方法的返回值

@AfterReturning中的属性returning,用来将通知方法的某个形参,接收目标方法的返回值

@AfterReturning(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->返回通知,方法名:"+methodName+",结果:"+result);
}
7.5.4.3 获取目标方法的异常

@AfterThrowing中的属性throwing,用来将通知方法的某个形参,接收目标方法的异常

@AfterThrowing(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->异常通知,方法名:"+methodName+",异常:"+ex);
}
7.5.4.4 环绕通知
@Around("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public Object aroundMethod(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;
}

7.6 切面的优先级

相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。

  • 优先级高的切面:外面
  • 优先级低的切面:里面

使用@Order注解可以控制切面的优先级:

  • @Order(较小的数):优先级高
  • @Order(较大的数):优先级低

在这里插入图片描述

7.7 AOP xml配置文件

<aop:config>
    <!--配置切面类-->
    <aop:aspect ref="loggerAspect">
        <aop:pointcut id="pointCut" expression="execution(* com.atguigu.aop.xml.CalculatorImpl.*(..))"/>
        <aop:before method="beforeMethod" pointcut-ref="pointCut"></aop:before>
        <aop:after method="afterMethod" pointcut-ref="pointCut"></aop:after>
        <aop:after-returning method="afterReturningMethod" returning="result" pointcut-ref="pointCut"></aop:after-returning>
        <aop:after-throwing method="afterThrowingMethod" throwing="ex" pointcut-ref="pointCut"></aop:after-throwing>
        <aop:around method="aroundMethod" pointcut-ref="pointCut"></aop:around>
    </aop:aspect>
    <aop:aspect ref="validateAspect" order="1">
        <aop:before method="validateBeforeMethod" pointcut-ref="pointCut"></aop:before>
    </aop:aspect>
</aop:config>

8 声明式事务处理

8.1 JdbcTemplate

8.1.1 简介

Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作

8.1.2 添加依赖信息

<dependencies>
        <!--引入context包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.6</version>
        </dependency>

        <!--引入context包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.6</version>
        </dependency>

        <!--声明式事务处理
            spring在执行持久化操作 与jdbc的整合过程,
            需要使用orm-jdbc-tx 三个jar包
        -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.6</version>
           <!-- <scope>test</scope>-->
        </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>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
    </dependencies>

8.1.3 配置jdbc.properties文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/atweb?serverTimezone=UTC
jdbc.username=root
jdbc.password=root

8.1.4 编辑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:util="http://www.springframework.org/schema/util"
       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/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--1.引入配置文件-->
    <context:property-placeholder location="classpath*:jdbc.properties"/>

    <!--2.配置数据源-->
    <bean id="dataSource" 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>

    <!--3.整合jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

8.1.5 编辑测试类

注意事项: BeanPropertyRowMapper 表示结果集封装的工具API

/**
 * @author 刘昱江
 * @className TestSpring
 * @description TODO
 * @date 2022/9/26 23:50
 */

//表示启动spring测试类 并且启动容器
@RunWith(SpringJUnit4ClassRunner.class)
//加载指定配置文件
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpring {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void save01(){
        String sql = "insert into demo_user values (null,?,?,?)";
        int rows = jdbcTemplate.update(sql,"jdbcTemplate",18,"男");
        System.out.println("业务执行成功:"+rows);
    }

    @Test
    public void delete(){
        String sql = "delete from demo_user where id=?";
        int rows = jdbcTemplate.update(sql,162);
        System.out.println("业务执行成功:"+rows);
    }

    @Test
    public void update(){
        String sql = "update demo_user set name=?,age=?,sex=? where id=?";
        int rows = jdbcTemplate.update(sql,"李四",18,"男",161);
        System.out.println("业务执行成功:"+rows);
    }


    @Test
    public void findOne(){
        String sql = "select * from demo_user where id=?";
        //封装User对象
        BeanPropertyRowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        User user = jdbcTemplate.queryForObject(sql,rowMapper,161);
        System.out.println(user);
    }

    @Test
    public void findList(){
        String sql = "select * from demo_user";
        //封装User对象
        BeanPropertyRowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        List list = jdbcTemplate.query(sql,rowMapper);
        list.forEach(System.out::println);
    }
}

8.2 声明式事务处理

8.2.1 编程事务

事务功能的相关操作全部通过自己编写代码来实现:

Connection conn = ...;
    
try {
    
    // 开启事务:关闭事务的自动提交
    conn.setAutoCommit(false);
    
    // 核心操作
    
    // 提交事务
    conn.commit();
    
}catch(Exception e){
    
    // 回滚事务
    conn.rollBack();
    
}finally{
    
    // 释放数据库连接
    conn.close();
    
}

编程式的实现方式存在缺陷:

  • 细节没有被屏蔽:具体操作过程中,所有细节都需要程序员自己来完成,比较繁琐。
  • 代码复用性不高:如果没有有效抽取出来,每次实现功能都需要自己编写代码,代码就没有得到复用。

8.2.2 声明式事务

既然事务控制的代码有规律可循,代码的结构基本是确定的,所以框架就可以将固定模式的代码抽取出来,进行相关的封装。

封装起来后,我们只需要在配置文件中进行简单的配置即可完成操作。

  • 好处1:提高开发效率
  • 好处2:消除了冗余的代码
  • 好处3:框架会综合考虑相关领域中在实际开发环境下有可能遇到的各种问题,进行了健壮性、性能等各个方面的优化

所以,我们可以总结下面两个概念:

  • 编程式自己写代码实现功能
  • 声明式:通过配置框架实现功能

8.3 构建层级代码完成事务测试

8.3.1 层级代码搭建

在这里插入图片描述

8.3.2 编辑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" xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" 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/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--1.引入配置文件-->
    <context:property-placeholder location="classpath*:jdbc.properties"/>

    <!--2.配置数据源-->
    <bean id="dataSource" 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>

    <!--3.整合jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--4.配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--添加数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--5.启动声明式事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--6.开启包扫描-->
    <context:component-scan base-package="com.atguigu"/>

</beans>

8.3.3 代码测试

图中先执行入库操作,之后发现运行时异常 ,默认条件下事务不会回滚.
在这里插入图片描述

8.4 @Transactional 介绍

8.4.1 注解标识的位置

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

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

 	@Override
    @Transactional
    public void addUser(User user) {

        userDao.addUser(user);
        int a = 1/0;
    }

8.4.2 事务属性-只读

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

 	@Transactional(readOnly = true)
    public void findUser(int id) {
        userDao.findUserById(id);
    }

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

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

8.4.3 事务属性-超时

事务在执行过程中,有可能因为遇到某些问题,导致程序卡住,从而长时间占用数据库资源。而长时间占用资源,大概率是因为程序运行出现了问题(可能是Java程序或MySQL数据库或网络连接等等)。

此时这个很可能出问题的程序应该被回滚,撤销它已做的操作,事务结束,把资源让出来,让其他正常程序可以执行。
概括来说就是一句话:超时回滚,释放资源。

	@Override
    @Transactional(timeout = 3)
    public void addUser(User user) {

        userDao.addUser(user);
    }

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

8.4.3 事务属性-回滚策略

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

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

  • rollbackFor属性:需要设置一个Class类型的对象

  • rollbackForClassName属性:需要设置一个字符串类型的全类名

  • noRollbackFor属性:需要设置一个Class类型的对象

  • rollbackFor属性:需要设置一个字符串类型的全类名

 	@Override
    @Transactional(timeout = 3,noRollbackFor = RuntimeException.class)
    public void addUser(User user) {
        userDao.addUser(user);
        int a = 1/0;
    }

8.4.4 事务属性-事务隔离级别

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

隔离级别一共有四种:

  • 读未提交:READ UNCOMMITTED

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

  • 读已提交:READ COMMITTED、

    要求Transaction01只能读取Transaction02已提交的修改。

  • 可重复读:REPEATABLE READ

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

  • 串行化:SERIALIZABLE

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

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

隔离级别 脏读 不可重复读 幻读
READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE

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

隔离级别 Oracle MySQL
READ UNCOMMITTED ×
READ COMMITTED √(默认)
REPEATABLE READ × √(默认)
SERIALIZABLE
②使用方式
@Transactional(isolation = Isolation.DEFAULT)//使用数据库默认的隔离级别
@Transactional(isolation = Isolation.READ_UNCOMMITTED)//读未提交
@Transactional(isolation = Isolation.READ_COMMITTED)//读已提交
@Transactional(isolation = Isolation.REPEATABLE_READ)//可重复读
@Transactional(isolation = Isolation.SERIALIZABLE)//串行化
事务属性:事务传播行为

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

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

@Transactional(propagation = Propagation.REQUIRES_NEW),表示不管当前线程上是否有已经开启的事务,都要开启新事务。

在这里插入图片描述

业务操作: 利用业务方法,

@Override
    @Transactional(propagation = Propagation.REQUIRED)  //1个事务
    public Integer addUser(User user) throws SQLException {
        deptService.addDept(new Dept(null,"数据库部门"));
        System.out.println("部门操作成功!!");
        int rows = userDao.addUser(user);
        System.out.println("用户操作成功!!");
        //int a = 1/0;
        return rows;
    }



### 8.4.5 基于XML的声明式事务
将Spring配置文件中去掉tx:annotation-driven 标签,并添加配置:
```xml
 <!--5.配置spring中的事务管理器
        解释:  该事务管理器中内部维护了AOP对于事务的控制 用户可以直接使用.
        同理:  如果用户需要自己控制事务 则实现特定的接口
        参数:  如果进行事务的控制 则必须添加数据源的支持.
    -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
<aop:config>
    <!-- 配置事务通知和切入点表达式 -->
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.atguigu.spring.tx.xml.service.impl.*.*(..))"></aop:advisor>
</aop:config>
<!-- tx:advice标签:配置事务通知 -->
<!-- id属性:给事务通知标签设置唯一标识,便于引用 -->
<!-- transaction-manager属性:关联事务管理器 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!-- tx:method标签:配置具体的事务方法 -->
        <!-- name属性:指定方法名,可以使用星号代表多个字符 -->
        <tx:method name="get*" read-only="true"/>
        <tx:method name="query*" read-only="true"/>
        <tx:method name="find*" read-only="true"/>
    
        <!-- read-only属性:设置只读属性 -->
        <!-- rollback-for属性:设置回滚的异常 -->
        <!-- no-rollback-for属性:设置不回滚的异常 -->
        <!-- isolation属性:设置事务的隔离级别 -->
        <!-- timeout属性:设置事务的超时属性 -->
        <!-- propagation属性:设置事务的传播行为 -->
        <tx:method name="save*" read-only="false" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/>
        <tx:method name="update*" read-only="false" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/>
        <tx:method name="delete*" read-only="false" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/>
    </tx:attributes>
</tx:advice>

注意事项

注意:基于xml实现的声明式事务,必须引入aspectJ的依赖

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-aspects</artifactId>
 <version>5.3.6</version>
</dependency>
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐