spring学习总结

前言

本文是我根据B站狂神(秦疆老师)的Spring5最新完整教程一视频整理得来,借鉴了秦老师的讲课内容。读者们也可以去B站看秦老师的其他精品教程,讲解的都非常详细到位,而且都是免费的。

视频链接:https://www.bilibili.com/video/BV1WE411d7Dv?spm_id_from=333.999.0.0

已经将学习过程中的代码托管到Gitee上:https://gitee.com/blossoming819/Spring-study.git

在以后的学习生活中还要多加运用,才能熟练掌握。

1、Spring概述

在这里插入图片描述

1.1、简介

  • Spring : 春天 —->给软件行业带来了春天
  • 2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。
  • 2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。
  • 很难想象Rod Johnson的学历 , 他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
  • Spring理念 : 使现有技术更加实用 . 本身就是一个大杂烩 , 整合现有的框架技术

官方文档:https://docs.spring.io/spring-framework/docs/current/reference/html/index.html

官方下载地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/

GitHub : https://github.com/spring-projects

1.2 、优点

  • Spring是一个开源免费的框架 , 容器 .

  • Spring是一个轻量级的框架 , 非侵入式的 ,不会对原有的类造成影响 .

  • 控制反转 IoC , 面向切面 Aop

  • 对事物的支持 , 对框架的支持

  • 一句话概括:Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。

1.3、 组成

在这里插入图片描述

Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式 .

在这里插入图片描述

组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:

  • 核心容器: 核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
  • Spring 上下文: Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
  • Spring AOP: 通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
  • Spring DAO: JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
  • Spring ORM: Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
  • Spring Web 模块: Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
  • Spring MVC 框架: MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。

1.4 、拓展

Spring Boot与Spring Cloud

  • Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务;
  • Spring Cloud是基于Spring Boot实现的;
  • Spring Boot专注于快速、方便集成的单个微服务个体,Spring Cloud关注全局的服务治理框架;
  • Spring Boot使用了约束优于配置的理念,很多集成方案已经帮你选择好了,能不配置就不配置 , Spring Cloud很大的一部分是基于Spring Boot来实现,Spring Boot可以离开Spring Cloud独立使用开发项目,但是Spring Cloud离不开Spring Boot,属于依赖的关系。
  • SpringBoot在SpringClound中起到了承上启下的作用,如果你要学习SpringCloud必须要学习SpringBoot。

在这里插入图片描述

2、 IoC基础

新建一个Maven项目

2.1、案例分析

需求:Service层调用不同的Dao层接口。

新建一个dao层接口

package com.princehan.dao;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 14:43
 */
public interface UserDao {
    void getUser();
}

实现dao层接口

package com.princehan.dao;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 14:43
 */
public class UserDaoImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("默认实现");
    }
}
package com.princehan.dao;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 16:31
 */
public class UserMySQLImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("MySQL实现");
    }
}
package com.princehan.dao;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 16:32
 */
public class UserSQLServerImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("SQLServer实现");
    }
}

新建一个service层接口

package com.princehan.service;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 14:44
 */
public interface UserService {
    void getUser();
}

实现service接口

package com.princehan.service;

import com.princehan.dao.UserDao;
import com.princehan.dao.UserDaoImpl;


/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 14:44
 */
public class UserServiceImpl implements UserService{
    private UserDao userDao = new UserDaoImpl();
    
    @Override
    public void getUser() {
        userDao.getUser();
    }
}

编写测试类

import org.junit.Test;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 16:39
 */
public class MyTest {
    @Test
    public void test() {
        UserServiceImpl userService = new UserServiceImpl();
        userService.getUser();
    }
}

我们要调用不同的dao层接口,就要在UserServiceImpl修改dao的接口,因为UserServiceImpl实例化dao层接口的类型是固定的,也就是根据不同的需求我们需要修改不同的代码,这显然不符合常理。

我们换一种思路,在UserServiceImpl并不固定dao层接口的类型,而是提供修改dao层类型的一个接口,可以用set方法实现。

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

测试类

@Test
public void test() {
    UserServiceImpl userService = new UserServiceImpl();
    userService.setUserDao(new UserDaoImpl());
    userService.getUser();
    userService.setUserDao(new UserMySQLImpl());
    userService.getUser();
    userService.setUserDao(new UserSQLServerImpl());
    userService.getUser();
}

仔细观察两种方式的区别:

以前所有东西都是由程序去进行控制创建 , 而现在是由我们自行控制创建对象 , 把主动权交给了调用者 . 程序不用去管怎么创建,怎么实现了 . 它只负责提供一个接口 .

这种思想 , 从本质上解决了问题 , 程序员不再去管理对象的创建了 , 更多的去关注业务的实现 . 耦合性大大降低 . 这也就是IOC的原型 !

2.2、IoC本质

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法, 也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

在这里插入图片描述

IoC是Spring框架的核心内容, 使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。

Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。

在这里插入图片描述

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

3、HelloSpring

3.1、编写第一个Spring程序

新建实体类

package com.princehan.pojo;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 18:18
 */
public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

导入Spring的依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.18</version>
</dependency>

编写Spring配置文件(beans.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--bean就是java对象 , 由Spring创建和管理-->
    <!--
    id表示对象名 class表示类的路径
    property name表示属性名 value 表示属性值 value的值根据set方法获得
    -->
    <bean id="hello" class="com.princehan.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

编写测试类

import com.princehan.pojo.Hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/12 18:30
 */
public class MyTest {
    @Test
    public void HelloSpring() {
        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //从Spring容器中获取对象
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

在这里插入图片描述

3.2、思考

Hello 对象是谁创建的 ?

答:hello 对象是由Spring创建的

Hello 对象的属性是怎么设置的 ?

答:hello 对象的属性是由Spring容器设置的

这个过程就叫控制反转 :

  • 控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的

  • 反转 : 程序本身不创建对象 , 而变成被动的接收对象 .

依赖注入 : 就是利用set方法来进行注入的.

IOC是一种编程思想,由主动的编程变成被动的接收

可以通过new ClassPathXmlApplicationContext()去浏览一下底层源码 .

3.3、修改第二章的案例

<?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">

    <bean id="daoImpl" class="com.princehan.dao.UserDaoImpl"/>
    <bean id="mysqlImpl" class="com.princehan.dao.UserMySQLImpl"/>
    <bean id="sqlServerImpl" class="com.princehan.dao.UserSQLServerImpl"/>
    <bean id="userServiceImpl" class="com.princehan.service.UserServiceImpl">
    	<!--value表示基本数据类型以及字符串 ref表示引用类型-->
        <property name="userDao" ref="sqlServerImpl"/>
    </bean>
</beans>
    @Test
    public void UserServiceTest() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
        userServiceImpl.getUser();
    }

4、IoC创建对象方式

4.1、通过无参构造方法来创建

实体类

public class User {
    private String name;

    public User() {
        System.out.println("user无参构造方法");
    }

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

    public void show() {
        System.out.println("name=" + name);
    }
}

编写配置文件

<?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">
    <bean id="user" class="com.princehan.pojo.User">

    </bean>
</beans>

编写测试类


    @Test
    public void NoArgsConstructor() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
    }

在这里插入图片描述
如果没有无参构造方法,这种方式会报错。

4.2、通过有参构造方法来创建

实体类

public class UserT {
    private String name;

    public UserT(String name) {
        this.name = name;
    }

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

    public void show() {
        System.out.println("name=" + name);
    }
}

编写配置文件

<!-- 第一种根据参数名字设置 name表示参数名-->
<constructor-arg name="name" value="张三"/>
<!-- 第二种根据参数下标设置 index从0开始-->
<constructor-arg index="0" value="李四"/>
<!-- 第三种根据参数类型设置 要求限定全类名-->
<constructor-arg type="java.lang.String" value="王五"/>

编写测试类

@Test
public void AllArgsConstructor() {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserT userT = (UserT) context.getBean("userT");
    userT.show();
}

5、Spring配置

5.1、 别名

alias 设置别名 , 为bean设置别名 , 可以设置多个别名

<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="userT" alias="userNew"/>

5.2、 Bean的配置

<!--bean就是java对象,由Spring创建和管理-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.kuang.pojo.Hello">
    <property name="name" value="Spring"/>
</bean>
  • id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
  • 如果配置id,又配置了name,那么name是别名
  • name可以设置多个别名,可以用逗号,分号,空格隔开
  • 如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;
  • class是bean的全限定名=包名+类名

5.3、 import

团队的合作通过import来实现 .

<import resource="{path}/beans.xml"/>

6、依赖注入(DI)

  • 依赖注入(Dependency Injection,DI)。

  • 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .

  • 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .

环境搭建


public class Address {
    private String address;
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    public void show() {
        System.out.print("name=" + name
                + "\naddress=" + address.getAddress()
                + "\nbooks="
        );
        for (String book : books) {
            System.out.print("<<" + book + ">>\t");
        }
        System.out.println("\n爱好:" + hobbys);
        System.out.println("card:" + card);
        System.out.println("games:" + games);
        System.out.println("wife:" + wife);
        System.out.println("info:" + info);
    }
}

6.1、构造器注入

根据无参构造和有参构造注入。

6.2、set注入 (重点)

  1. 常量注入
<bean id="address" class="com.princehan.pojo.Address">
    <property name="address" value="河南"/>
</bean>
  1. Bean注入

注意点:这里的值是一个引用,ref

<bean id="address" class="com.princehan.pojo.Address">
    <property name="address" value="河南"/>
</bean>
<bean id="student" class="com.princehan.pojo.Student">
    <property name="name" value="王子"/>
    <property name="address" ref="address"/>
</bean>
  1. 数组注入
<property name="books">
   <array>
       <value>Java</value>
       <value>JavaWeb</value>
       <value>MyBatis</value>
       <value>Spring</value>
       <value>SpringMVC</value>
   </array>
</property>
  1. list注入
<property name="hobbys">
    <list>
        <value>听歌</value>
        <value>看剧</value>
        <value>敲码</value>
    </list>
</property>
  1. map注入
<property name="card">
    <map>
        <entry key="IDcard" value="56156156"/>
        <entry key="StudentCard" value="45485"/>
    </map>
</property>
  1. set注入
<property name="games">
    <set>
        <value>王者</value>
        <value>吃鸡</value>
    </set>
</property>
  1. properties注入
<property name="info">
    <props>
        <prop key="user">root</prop>
        <prop key="pwd">0925</prop>
    </props>
</property>
  1. 空指针注入
<property name="wife"><null/></property>

编写测试类

    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        student.show();
    }

6.3、拓展注入实现

public class User {
    private String name;
    private int age;
    public User() {

    }
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
<!--无参构造器-->
<bean id="user" class="com.princehan.pojo.User" p:name="张三" p:age="18"/>
<!--有参构造器-->
<bean id="user2" class="com.princehan.pojo.User" c:name="李四" c:age="19"/>

需要在xml中导入约束(头部)

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

6.4、Bean的作用域

在这里插入图片描述
在这里着重介绍单例模式和原型模式。

单例模式,在Spring IoC容器中只有一份示例,通过单例模式创造的对象是相同的,原型模式则相反。

<!--单例模式  默认开启-->
<bean id="userSingleton" class="com.princehan.pojo.User" c:name="王子" c:age="18" scope="singleton"/>
<!--原型-->
<bean id="userProtoType" class="com.princehan.pojo.User" c:name="王子" c:age="18" scope="prototype"/>
@Test
public void ScopeTest() {
    ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
    User userSingleton = context.getBean("userSingleton", User.class);
    User userSingleton1 = context.getBean("userSingleton", User.class);
    System.out.println("Singleton模式是否创建的是同一个对象:");
    System.out.println(userSingleton == userSingleton1);
    User userProtoType = context.getBean("userProtoType", User.class);
    User userProtoType1 = context.getBean("userProtoType", User.class);
    System.out.println("ProtoType模式是否创建的是同一个对象:");
    System.out.println(userProtoType == userProtoType1);
}

在这里插入图片描述

7、Bean的自动装配

  • 自动装配是使用spring满足bean依赖的一种方法
  • spring会在应用上下文中为某个bean寻找其依赖的bean。

Spring中bean有三种装配机制,分别是:

  1. 在xml中显式配置;
  2. 在java中显式配置;
  3. 隐式的自动装配。【重要】

7.1、测试环境搭建

实体类

public class Cat {
    public void shout() {
        System.out.println("喵");
    }
}
public class Dog {
    public void shout() {
        System.out.println("汪");
    }
}
public class People {
    private Cat cat;
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

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

    public String getName() {
        return name;
    }

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

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

编写bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="cat" class="com.princehan.pojo.Cat"/>
    <bean id="dog" class="com.princehan.pojo.Dog"/>
    <bean id="people" class="com.princehan.pojo.People">
        <property name="name" value="王子"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>
</beans>

编写测试

@Test
public void test() {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    People people = context.getBean("people", People.class);
    people.getDog().shout();
    people.getCat().shout();
}

在上面的例子中我们需要显式的装配people的属性,如果使用自动装配,就不用显示装配属性。

7.2、byName和byType

自动装配两种类型:

  1. byName,根据需要装配属性的对象的属性名进行装配,属性名不符合就会装配失败。
  2. byName,根据需要装配属性的对象的类型名进行装配,类型名不符合就会装配失败。
<!--byType cat1不会报错-->
<bean id="cat1" class="com.princehan.pojo.Cat"/>
<bean id="dog" class="com.princehan.pojo.Dog"/>
<bean id="people" class="com.princehan.pojo.People" autowire="byType">

<!--byName cat1会报错-->
<bean id="cat1" class="com.princehan.pojo.Cat"/>
<bean id="dog" class="com.princehan.pojo.Dog"/>
<bean id="people" class="com.princehan.pojo.People" autowire="byName">

<!--报错 cat1和cat-->
<bean id="cat1" class="com.princehan.pojo.Cat"/>
<bean id="cat" class="com.princehan.pojo.Cat"/>
<bean id="dog" class="com.princehan.pojo.Dog"/>
<bean id="people" class="com.princehan.pojo.People" autowire="byType">
<!--能找到cat 不会报错-->
<bean id="cat1" class="com.princehan.pojo.Cat"/>
<bean id="cat" class="com.princehan.pojo.Cat"/>
<bean id="dog" class="com.princehan.pojo.Dog"/>
<bean id="people" class="com.princehan.pojo.People" autowire="byName">

7.3、使用注解装配

jdk1.5开始支持注解,spring2.5开始全面支持注解。

首先需要在beans.xml中开启注解的约束。

xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd

开启注解

<context:annotation-config/>

多写几个bean测试一下

    <bean id="cat" class="com.princehan.pojo.Cat"/>
    <bean id="cat1" class="com.princehan.pojo.Cat"/>
    <bean id="dog" class="com.princehan.pojo.Dog"/>
    <bean id="dog1" class="com.princehan.pojo.Dog"/>
    <bean id="people" class="com.princehan.pojo.People">

@Autowired

    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
  • @Autowired 通过byType方式进行自动装配,可以作用在属性上,也可以作用在set方法上,使用 @Autowired 可以不用写set方法。
  • @Autowired 无法通过byType方式进行自动装配时,可以配合另一个注解 @Qualifier(value = "cat1") 进行byName方式装配
  • @Qualifier 不能单独使用。
    @Autowired
    @Qualifier(value = "cat1")
    private Cat cat;

@Resource

  • @Resource 如有指定的name属性,先按该属性进行byName方式查找装配;
  • 其次再进行默认的byName方式进行装配;
  • 如果以上都不成功,则按byType的方式自动装配。
  • 都不成功,则报异常。
    @Resource
    private Cat cat;
    @Resource(name = "dog")
    private Dog dog;

7.4、小结

@Autowired@Resource 异同:

  • @Autowired 与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
  • @Autowired 默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
  • @Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
  • 它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired 先byType,@Resource 先byName。

8、使用注解开发

使用注解开发需要引入aop的包,但之前我们引入了spring-webmvc的包,会自动引入aop的包。
在这里插入图片描述
在配置文件当中,还得要引入一个context约束

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

8.1、Bean的注解实现

我们之前都是使用 bean 的标签进行bean注入,但是实际开发中,我们一般都会使用注解!

开启注解

<context:annotation-config/>

添加要扫描的包

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

新建实体类 用注解方式注入bean

@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
    public String name = "王子";
}

测试

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

8.2、属性的注入

属性的注入用 @Value() 实现

@Component
public class Address {
    @Value("河南")
    public String address;
}
@Component
// <bean id="user" class="com.princehan.pojo.User"/>
public class User {

    //<property name="name" value="王子"/>
    public String name;
    public Address address;
    
    @Autowired
    public void setAddress(Address address) {
        this.address = address;
    }

    @Value("王子")
    public void setName(String name) {
        this.name = name;
    }
}

8.3、衍生注解

@Component 三个衍生注解

为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。

@Controller :web层
@Service :service层
@Repository :dao层

写上这些注解,就相当于将这个类交给Spring管理装配了!

8.4、自动装配注解

在 7.3、使用注解中已经介绍过了,这里就不再过多赘述了。

8.5、作用域

@Scope()

singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收

8.6、小结

XML与注解比较

  • XML可以适用任何场景 ,结构清晰,维护方便

  • 注解不是自己提供的类使用不了,开发简单方便

xml与注解整合开发 :推荐最佳实践

  • xml管理Bean
  • 注解完成属性注入
  • 使用过程中, 可以不用扫描,扫描是为了类上的注解
<context:annotation-config/>

作用:

  • 进行注解驱动注册,从而使注解生效

  • 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册

  • 如果不扫描包,就需要手动配置bean

  • 如果不加注解驱动,则注入的值为null!

8.7、使用Java类进行配置

JavaConfig 原来是 Spring 的一个子项目,它通过 Java 类的方式提供 Bean 的定义信息,在 Spring4 的版本, JavaConfig 已正式成为 Spring4 的核心功能 。

编写实体类

@Component
public class User {
    @Value("王子")
    public String name;
}

编写配置类

@Configuration  //代表这是一个配置类
public class SpringConfig {

    @Bean //通过方法注册一个bean,返回值为bean的类型,方法名就是bean的id
    public User user() {
        return new User();
    }
}

测试

@Test
public void test() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
    User user = context.getBean("user", User.class);
    System.out.println(user.name);
}

如何引入其他的配置文件呢?

新建一个配置类

@Configuration
public class Config2 {
}

使用注解引入

@Configuration
@Import(Config2.class)
public class SpringConfig {

    @Bean
    public User user() {
        return new User();
    }
}

使用Java类进行配置在springboot和springcloud用的比较多。

9、AOP

9.1、什么是AOP

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。建议在学习AOP之前先了解一下代理模式。
在这里插入图片描述

9.2、 Aop在Spring中的作用

提供声明式事务;允许用户自定义切面

横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ….

切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。

通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

目标(Target):被通知对象。

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

切入点(PointCut):切面通知 执行的 “地点”的定义。

连接点(JointPoint):与切入点匹配的执行点。
在这里插入图片描述
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
在这里插入图片描述
即 Aop 在 不改变原有代码的情况下 , 去增加新的功能 。

9.3、 使用Spring实现Aop

【重点】使用AOP织入,需要导入一个依赖包!

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.8</version>
</dependency>
9.3.1、通过spring API实现

第一种方法:

新建一个接口并继承

public interface UserService {
    void add();
    void delete();
    void update();
    void select();
}
public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("调用了add方法");
    }

    @Override
    public void delete() {
        System.out.println("调用了delete方法");
    }

    @Override
    public void update() {
        System.out.println("调用了update方法");
    }

    @Override
    public void select() {
        System.out.println("调用了select方法");
    }
}

接着编写增强类 , 一个前置增强 一个后置增强

public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        assert target != null;
        System.out.println("执行了" + target.getClass().getName()
                + "的" + method.getName() + "方法,"
                + "返回值:" + returnValue);
    }
}
public class BeforeLog implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + "的" + method.getName() + "方法执行了");
    }
}

注入bean

    <bean id="userService" class="com.princehan.service.UserServiceImpl"/>
    <bean id="afterLog" class="com.princehan.Log.AfterLog"/>
    <bean id="beforeLog" class="com.princehan.Log.BeforeLog"/>

配置切入点和通知

<aop:config>
    <!--execution(访问修饰符[可选] 返回值类型*通配 全类名.方法名(参数 ..表示所有参数))-->
    <aop:pointcut id="pointcut" expression="execution(* com.princehan.service.UserServiceImpl.*(..))"/>
    <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
    <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>

测试
在这里插入图片描述
== Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解这一块 .==

Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .

第二种方法

自定义类来实现Aop

目标业务类不变依旧是userServiceImpl

自定义一个切入类

public class DiyPointCut {
    public void before() {
        System.out.println("方法执行前");
    }
    public void after() {
        System.out.println("方法执行后");
    }
}

在spring中配置

<bean id="diy" class="com.princehan.diy.DiyPointCut"/>
<aop:config>
    <!--自定义切面-->
    <aop:aspect ref="diy">
        <!--切入点-->
        <aop:pointcut id="pointcut" expression="execution(* com.princehan.service.UserServiceImpl.*(..))"/>
        <!--通知-->
        <aop:before method="before" pointcut-ref="pointcut"/>
        <aop:after method="after" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>

在这里插入图片描述

9.3.2、使用注解实现

编写一个注解实现的增强类

@Aspect
public class AnnotationPointCut {
    @Before("execution(* com.princehan.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("执行方法前");
    }

    @After("execution(* com.princehan.service.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("执行方法后");
    }

    @AfterReturning("execution(* com.princehan.service.UserServiceImpl.*(..))")
    public void afterReturning() {
        System.out.println("afterReturning");
    }

    @Around("execution(* com.princehan.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前");
        pjp.proceed();
        System.out.println("环绕后");
    }
}

配置spring

<bean id="annotationPointCut" class="com.princehan.diy.AnnotationPointCut"/>
 <!--开启注解支持-->
 <aop:aspectj-autoproxy/>

测试

@Test
public void AnnotationTest() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = context.getBean("userService", UserService.class);
    userService.select();
}

在这里插入图片描述

10、整合MyBatis

这一章主要讲解如何整合MyBatis和Spring框架。

什么是 MyBatis-Spring?

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。

知识基础

在开始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 这两个框架和有关它们的术语。

导入所需的所有依赖

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.28</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.22</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.18</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.7</version>
    </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.18</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.8</version>
    </dependency>
</dependencies>

配置maven路径过滤

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

编写实体类

@Data
public class User {
    private int id;
    private String name;
    private String pwd;

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

编写MyBatis工具类

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream resourcestream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourcestream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }
}

编写Mapper接口

public interface UserMapper {
    List<User> selectUser();
}

如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
</dependency>

要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类。

在 MyBatis-Spring 中,可使用SqlSessionFactoryBean来创建 SqlSessionFactory。 要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>

注意:SqlSessionFactory需要一个 DataSource(数据源)。 这可以是任意的DataSource,只需要和配置其它 Spring 数据库连接一样配置它就可以了。

在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory 的。 而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean来创建。

在 MyBatis 中,你可以使用 SqlSessionFactory 来创建 SqlSession。一旦你获得一个 session 之后,你可以使用它来执行映射了的语句,提交或回滚连接,最后,当不再需要它的时候,你可以关闭 session

SqlSessionFactory 有一个唯一的必要属性:用于 JDBC 的 DataSource。这可以是任意的 DataSource 对象,它的配置方法和其它 Spring 数据库连接是一样的。

一个常用的属性是 configLocation,它用来指定 MyBatis 的 XML 配置文件路径。它在需要修改 MyBatis 的基础配置非常有用。通常,基础配置指的是 <settings><typeAliases>元素。

需要注意的是,这个配置文件并不需要是一个完整的 MyBatis 配置。确切地说,任何环境配置(<environments>),数据源(<DataSource>)和 MyBatis 的事务管理器(<transactionManager>)都会被忽略。SqlSessionFactoryBean 会创建它自有的 MyBatis 环境配置(Environment),并按要求设置自定义环境的值。

SqlSessionTemplate是 MyBatis-Spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession

模板可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用 SqlSessionTemplate 来替换 MyBatis 默认的 DefaultSqlSession 实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。

可以使用 SqlSessionFactory作为构造方法的参数来创建 SqlSessionTemplate 对象。

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

现在,这个 bean 就可以直接注入到你的 DAO bean 中了。你需要在你的 bean 中添加一个 SqlSession 属性,就像下面这样:

public class UserMapperImpl implements UserMapper {

    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

按下面这样,注入 SqlSessionTemplate

<bean id="userMapper" class="com.princehan.mapper.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
</bean>

10.1、整合方式一

配置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">
</beans>

** 替换数据源**

    <!--使用spring的数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatisdatabase?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value="0925"/>
    </bean>

配置SqlSessionFactory 关联MyBatis

    <!--创建sqlSessionFactory  这就相当于一个mybatis-config.xml 可以在这里配置MyBatis-->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!--绑定mybatis配置文件-->
      <property name="configLocation" value="classpath:mybatis-config.xml"/>
      <property name="mapperLocations" value="classpath:com/princehan/mapper/*.xml"/>
  </bean>

注意:

 <property name="mapperLocations" value="classpath:com/princehan/mapper/*.xml"/>
 与mybatis中的mapper映射二选一

注册sqlSessionTemplate,关联sqlSessionFactory

<!--创建sqlSessionFactory  这就相当于一个mybatis-config.xml 可以在这里配置MyBatis-->


    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

注册bean实现

    <bean id="userMapper" class="com.princehan.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

** MyBatis配置**

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>
    <properties resource="db.properties"/>
    <settings>
        <!--日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--显示开启全局缓存 默认开启-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.princehan.pojo"/>
    </typeAliases>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.princehan.mapper.UserMapper">
    <select id="selectUser" resultType="User">
        select * from user
    </select>
</mapper>

测试

    @Test
    public void test1() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        userMapper.selectUser();
    }

在这里插入图片描述

10.2、整合方式二

mybatis-spring1.2.3版以上的才有这个 .

官方文档截图 :

dao继承Support类 , 直接利用 getSqlSession()获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate, 而且对事务的支持更加友好 . 可跟踪源码查看

在这里插入图片描述

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

注册bean

    <bean id="userMapper2" class="com.princehan.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

测试

@Test
public void test2() {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
    UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
    userMapper.selectUser();
}

在这里插入图片描述

11、事务

11.1、回顾事务

事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!
事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。
事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。

事务四个属性ACID

原子性(atomicity)

  • 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用

一致性(consistency)

  • 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中

隔离性(isolation)

  • 可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏

持久性(durability)

  • 事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中

11.2、测试

新建一个接口

public interface UserMapper {
    List<User> selectUser();
    int addUser(User user);
    int deleteUser(int id);
}

编写MyBatis映射

<mapper namespace="com.princehan.mapper.UserMapper">
    <select id="selectUser" resultType="User">
        select * from user
    </select>
    <insert id="addUser" parameterType="User">
        insert into user(id, name, pwd) values (#{id}, #{name}, #{pwd})
    </insert>
    <delete id="deleteUser" parameterType="int">
        deletes from user where id = #{id}
    </delete>
</mapper>

故意写错一个sql语句deletes

编写实现类

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> selectUser() {
        User user = new User(6, "王子", "123456");
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(user);
        mapper.deleteUser(4);
        return mapper.selectUser();
    }

    @Override
    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    @Override
    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}

测试

    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        userMapper.selectUser();
    }

分析

  • 测试发现尽管程序出错,但是数据依然加入数据库中了,不合理。

  • 没有进行事务的管理;我们想让他们都成功才成功,有一个失败,就都失败,我们就应该需要事务

  • 以前我们都需要自己手动管理事务,十分麻烦,但是Spring给我们提供了事务管理,我们只需要配置即可;

11.3、Spring中的事务管理

Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。

编程式事务管理

  • 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
  • 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码

声明式事务管理

  • 一般情况下比编程式事务好用。
  • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
  • 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。

使用Spring管理事务,注意头文件的约束导入 : tx

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

事务管理器

  • 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。

  • 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。

jdbc事务管理器

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

配置事务的通知

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="add" propagation="REQUIRED"/>
        <tx:method name="delete" propagation="REQUIRED"/>
        <tx:method name="update" propagation="REQUIRED"/>
        <tx:method name="search*" propagation="REQUIRED"/>
        <tx:method name="get" read-only="true"/>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

spring事务传播特性:

事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:

  • propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
  • propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
  • propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
  • propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
  • propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
  • propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作

Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。

配置AOP

导入aop的头文件!

<!--配置aop织入事务-->
    <!--配置aop织入事务-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.princehan.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

进行测试

删掉刚才插入的数据,再次测试!

@Test
public void test() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
    userMapper.selectUser();
}

思考问题?

为什么需要配置事务?

  • 如果不配置,就需要我们手动提交控制事务;

  • 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值