Spring学习

Spring

1. Spring介绍

官网 : http://spring.io/

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

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

Maven依赖:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.4</version>
</dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.4</version>
</dependency>

优点:Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。

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

  • Spring是一个轻量级的框架,非侵入式的;

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

  • 对事物的支持,对框架整合的支持;

  • .......

组成:

img

组成 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。

拓展: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

2.1 IOC理论推导

之前的业务实现步骤:

  1. 先写一个UserDao接口;

    public interface UserDao {
        void getUser();
    }
  2. 再去写Dao的实现类;

    public class UserDaoImpl implements UserDao{
        public void getUser() {
            System.out.println("默认地获取用户数据!");
        }
    }
  3. 然后去写UserService的接口;

    public interface UserService {
        void getUser();
    }
  4. 最后写Service的实现类;

    public class UserServiceImpl implements UserService{
        // 组合
        private UserDao userDao = new UserDaoImpl();
        public void getUser() {
            userDao.getUser();
        }
    }
  5. 测试。

    @Test
    public void testGetUser(){
        // 用户实际调用的是业务层,dao层无需接触
        UserService userService = new UserServiceImpl();
        userService.getUser();
    }

当我们增加一个使用Mysql获取用户数据的UserDao的实现类时,

public class UserDaoMysqlImpl implements UserDao{
    public void getUser() {
        System.out.println("Mysql获取用户数据!");
    }
}

不得不在service实现类里更改对应的实现,

public class UserServiceImpl implements UserService{
    // private UserDao userDao = new UserDaoImpl();
    private UserDao userDao = new UserDaoMysqlImpl();
    public void getUser() {
        userDao.getUser();
    }
}

问题:假设我们对UserDao需要多种不同的实现类(如Oracle获取用户数据等),每次需要修改大量代码,使得设计的耦合性太高。

解决办法:可以在需要用到他的地方,不去实现它,而是留出一个接口,然后利用set方法实现值的注入;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
    // 利用set方法动态实现值的注入
    public void setUserDao(UserDao userDao){
        this.userDao = userDao;
    }
    public void getUser() {
        userDao.getUser();
    }
}

测试:

@Test
public void testGetUser(){
    UserService userService = new UserServiceImpl();
    ((UserServiceImpl) userService).setUserDao(new UserDaoMysqlImpl());
    userService.getUser();
}

以前所有东西都是由程序去进行控制创建,而现在是由我们自行控制创建对象,把主动权交给了调用者。程序不用去管怎么创建,怎么实现了。它只负责提供一个接口。这种思想,从本质上解决了问题,我们程序员不再去管理对象的创建了,更多的去关注业务的实现。耦合性大大降低。这也就是IOC的原型 。

2.2 IOC本质

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

IoC是Spring框架的核心内容,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。

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

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

参考链接:https://blog.csdn.net/qq_33369905/article/details/106647330

2.3 HelloSpring

  1. 导入Maven依赖;

  2. 编写实体类;

    public class Hello {
        private String name;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void print(){
            System.out.println("Hello, " + name + "!");
        }
    }
  3. 编写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 id="hello" class="com.wang.pojo.Hello">
            <property name="name" value="Spring"/>
        </bean>
    </beans>
  4. 测试。

    @Test
    public void testHelloSpring(){
        // 获取Spring上下文对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello = (Hello) context.getBean("hello");
        hello.print();
    }
  • Hello 对象是谁创建的?hello 对象是由Spring创建的。

  • Hello 对象的属性是怎么设置的?hello 对象的属性是由Spring容器设置的。

这个过程就叫控制反转 :

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

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

同样地,在IOC理论推导使用的案例中,也可以添加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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="DefaultImpl" class="com.wang.dao.UserDaoImpl"/>
    <bean id="MysqlImpl" class="com.wang.dao.UserDaoMysqlImpl"/>
    <bean id="ServiceImpl" class="com.wang.service.UserServiceImpl">
        <!--注意: 这里的name并不是属性 , 而是set方法后面的那部分 , 首字母小写-->
        <!--使用Mysql获取数据将ref改为MysqlImpl即可,无需修改代码-->
        <property name="userDao" ref="DefaultImpl"/>
    </bean>
</beans>

测试。

@Test
public void testIocGetUser(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
    UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");
    serviceImpl.getUser();
}

2.4 IOC 创建对象方式

使用无参构造方法创建对象(默认)

  1. User.java

    package com.wang.pojo;
    
    public class User {
        private String name;
        public User() {
            System.out.println("User无参构造");
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void print(){
            System.out.println("name = " + name);
        }
    }
  2. 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 id="user" class="com.wang.pojo.User">
            <property name="name" value="Cooky"/>
        </bean>
    </beans>
  3. 测试

    @Test
    public void testConstructorWithoutParam(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    
        User user = (User) context.getBean("user");
        System.out.println("=======================");
        user.print();
    }
    // 结果
    User无参构造
    =======================
    name = Cooky

使用有参构造方法创建对象

  1. User2.java

    package com.wang.pojo;
    
    public class User2 {
        private String name;
        public User2(String name) {
            this.name = name;
            System.out.println("User有参构造");
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void print(){
            System.out.println("name = " + name);
        }
    }
  2. beans.xml

    <!-- 方式一:通过参数下标赋值 -->
    <bean id="user2" class="com.wang.pojo.User2">
        <constructor-arg index="0" value="Java"/>
    </bean>
    <!-- 方式二:根据参数名字设置 -->
    <bean id="user2" class="com.wang.pojo.User2">
        <constructor-arg name="name" value="Java"/>
    </bean>
    <!-- 方式三:根据参数类型设置 (不推荐) -->
    <bean id="user2" class="com.wang.pojo.User2">
        <constructor-arg type="java.lang.String" value="Java"/>
    </bean>
  3. 测试

    @Test
    public void testConstructorWithParam(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    
        User2 user = (User2) context.getBean("user2");
        System.out.println("=======================");
        user.print();
    }
    // 结果
    User有参构造
    =======================
    name = Java

结论:在配置文件beans.xml加载时,其中管理的所有对象都已经初始化了。

3. Spring配置 - 基于xml的配置

别名

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

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

Bean的配置

<!--
   id: bean的标识符,唯一,如果没有配置id,name就是默认标识符
       如果配置id,又配置了name,那么name是别名
   name:可以设置多个别名,可以用逗号,分号,空格隔开
       如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象
   class:bean的全限定名=包名+类名
   -->
<bean id="user1" class="com.wang.pojo.User" name="user1New">
    <property name="name" value="Python"/>
</bean>

import

一般用于团队开发中使用,将多个配置文件导入合并为一个。

<import resource="beans0.xml"/>
<import resource="beans1.xml"/>
<import resource="beans2.xml"/>

4. 依赖注入

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

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

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

4.1 构造器注入

参考使用有参构造方法创建IOC对象

4.2 Set方式注入(重点)

bean | ref | idref | list | set | map | props | value | null

  1. 实体类,添加get、set方法和toString方法

    public class Address {
        private String address;
    }
    public class Student {
        private String name;
        private Address address;
        private String[] books;
        private List<String> hobbies;
        private Map<String, String> card;
        private Set<String> games;
        private String wife;
        private Properties info;
    }
  2. 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 id="address" class="com.wang.pojo.Address">
            <property name="address" value="北京"/>
        </bean>
    
        <bean id="student" class="com.wang.pojo.Student">
            <!-- 1. 普通值 -->
            <property name="name" value="Tony"/>
            <!-- 2. bean -->
            <property name="address" ref="address"/>
            <!-- 3. 数组 -->
            <property name="books">
                <array>
                    <value>红楼梦</value>
                    <value>西游记</value>
                    <value>水浒传</value>
                    <value>三国演义</value>
                </array>
            </property>
            <!-- 4. List -->
            <property name="hobbies">
                <list>
                    <value></value>
                    <value></value>
                    <value>rap</value>
                </list>
            </property>
            <!-- 5. Map -->
            <property name="card">
                <map>
                    <entry key="身份证" value="123456"/>
                    <entry key="银行卡" value="654321"/>
                </map>
            </property>
            <!-- 6. Set -->
            <property name="games">
                <set>
                    <value>人类一败涂地</value>
                    <value>Overcooked</value>
                </set>
            </property>
            <!--  7. null -->
            <property name="wife">
                <null/>
            </property>
            <!-- 8. props -->
            <property name="info">
                <props>
                    <prop key="学号">111222333</prop>
                    <prop key="性别"></prop>
                </props>
            </property>
        </bean>
    </beans>
  3. 测试

    @Test
    public void testDI(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }
    // 结果
    Student{
    name='Tony', 
    address=Address{address='北京'}, 
    books=[红楼梦, 西游记, 水浒传, 三国演义], 
    hobbies=[唱, 跳, rap], 
    card={身份证=123456, 银行卡=654321}, 
    games=[人类一败涂地, Overcooked], 
    wife='null', 
    info={学号=111222333, 性别=男}
    }

4.3 拓展方式注入

p命名空间注入 : properties

需要在头文件中加入约束文件(xmlns:p="http://www.springframework.org/schema/p")

<bean id="user" class="com.wang.pojo.User" p:name="Cooky"/>

c 命名空间注入 : constructor

需要在头文件中加入约束文件(xmlns:c="http://www.springframework.org/schema/c")

<bean id="user2" class="com.wang.pojo.User" c:name="Cooky"/>

4.4 bean的作用域

Singleton

当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。要在XML中将bean定义成singleton,可以这样配置:

<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">

Prototype

当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。在XML中将bean定义成prototype,可以这样配置:

<bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>  

或者

<bean id="account" class="com.foo.DefaultAccount" singleton="false"/> 

Request

当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例;即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

<bean id="loginAction" class="cn".csdn.LoginAction" scope="request"/>

针对每次HTTP请求,Spring容器会根据loginAction bean的定义创建一个全新的LoginAction bean实例,且该loginAction bean实例仅在当前HTTP request内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginAction bean定义创建的实例,将不会看到这些特定于某个请求的状态变化。当处理请求结束,request作用域的bean实例将被销毁。

Session

当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

针对某个HTTP Session,Spring容器会根据userPreferences bean定义创建一个全新的userPreferences bean实例,且该userPreferences bean仅在当前HTTP Session内有效。与request作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session中根据userPreferences创建的实例,将不会看到这些特定于某个HTTP Session的状态变化。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉。

5. bean的自动装配

  • 自动装配是使用spring满足bean依赖的一种方法;

  • spring会在应用上下文中为某个bean寻找其依赖的bean。

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

  1. 在xml中显式配置;

  2. 在java中显式配置;

  3. 隐式的bean发现机制和自动装配(重点)。

5.1 环境搭建

手动装配bean(在xml中显式配置):

  1. 实体类

    public class Cat {
        public void shout(){
            System.out.println("喵喵喵~");
        }
    }
    public class Dog {
        public void shout(){
            System.out.println("汪汪汪~");
        }
    }
    public class People {        // 省略get、set和toString方法
        private String name;
        private Cat cat;
        private Dog dog;
    }
  2. 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 id="cat" class="com.wang.pojo.Cat"/>
        <bean id="dog" class="com.wang.pojo.Dog"/>
    
        <bean id="people" class="com.wang.pojo.People">
            <property name="name" value="Kyla"/>
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
        </bean>
    </beans>
  3. 测试

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

5.2 自动装配方法

方式一:autowire byName (按名称自动装配)

<bean id="cat" class="com.wang.pojo.Cat"/>
<bean id="dog" class="com.wang.pojo.Dog"/>

<bean id="people" class="com.wang.pojo.People" autowire="byName">
    <property name="name" value="Kyla"/>
</bean>

当一个bean节点带有 autowire byName的属性时:①将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat;②去spring容器中寻找是否有此字符串名称id的对象;③如果有,就取出注入;如果没有,就报空指针异常。

注意:使用byName时,bean的id名称必须与set方法名一致,且唯一。

方式二:autowire byType (按类型自动装配)

<bean id="cat" class="com.wang.pojo.Cat"/>
<bean id="dog" class="com.wang.pojo.Dog"/>

<bean id="people" class="com.wang.pojo.People" autowire="byType">
    <property name="name" value="Kyla"/>
</bean>

注意:使用byType时,bean的class不能创建其它的bean。

方式三:使用注解

准备工作:

  1. 添加约束文件:在spring配置文件中引入context文件头

  2. 配置注解支持

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

@Autowired

  • @Autowired是按类型自动转配的,不支持id匹配(当该类型有多个bean时,匹配id为set方法的bean,若匹配不到,则会报错);

  • 可以在类中属性上使用,也可以在类中set方法上使用;使用该注解时甚至可以不用编写类的set方法。

  1. 实体类

    public class People {
        private String name;
        @Autowired
        private Cat cat;
        @Autowired
        private Dog dog;
    }
  2. beans.xml

    <bean id="cat" class="com.wang.pojo.Cat"/>
    <bean id="dog" class="com.wang.pojo.Dog"/>
    <bean id="people" class="com.wang.pojo.People"/>
  3. 测试

注:@Autowired(required=false) :false,对象可以为null;true,对象必须存对象,不能为null(默认)。

@Autowired(required = false)
private Cat cat;

@Qualifier

  • @Autowired是根据类型byType自动装配的,加上@Qualifier则可以根据byName的方式自动装配;

  • @Qualifier不能单独使用,需要与@Autowired配合使用。

  1. 实体类

    public class People {
        private String name;
        @Autowired
        private Cat cat;
        @Autowired
        @Qualifier(value = "dog1")
        private Dog dog;
    }
  2. beans.xml

    <bean id="cat" class="com.wang.pojo.Cat"/>
    <bean id="dog1" class="com.wang.pojo.Dog"/>
    <bean id="dog2" class="com.wang.pojo.Dog"/>
    <bean id="people" class="com.wang.pojo.People"/>
  3. 测试

@Resource

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

  • 前两者是spring框架的注解,此注解是javax自带的注解。

  1. 实体类

    public class People {
        private String name;
        @Resource
        private Cat cat;
        @Resource
        private Dog dog;
    }
  2. beans.xml

    <bean id="cat" class="com.wang.pojo.Cat"/>
    <bean id="dog" class="com.wang.pojo.Dog"/>
    <bean id="people" class="com.wang.pojo.People"/>
  3. 测试

与@Qualifier类似,@Resource也可以指定name进行bean对象匹配

@Resource(name = "cat1")
private Cat cat;

小结

@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。

6. Spring配置 - 基于注解的配置

在spring4之后,想要使用注解形式,必须得要引入aop的包;在bean配置文件当中,还得要引入一个context约束和配置注解支持。

6.1 bean的实现

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

  1. 实体类

    // 相当于配置文件中 <bean id="user" class="当前注解的类"/>
    @Component("user")
    public class User {
        public String name;
    }
  2. 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"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
        <!--指定注解扫描包-->
        <context:component-scan base-package="com.wang.pojo"/>
        <context:annotation-config/>
    </beans>
  3. 测试

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

6.2 属性注入

  • 可以不用提供set方法,直接在直接名上添加@value("值");

    @Component("user")
    public class User {
        // 相当于配置文件中 <property name="name" value="Kyla"/>
        @Value("Kyla")
        public String name;
    }
  • 如果提供了set方法,在set方法上添加@value("值")。

    @Component("user")
    public class User {
        public String name;
    
        @Value("Kyla")
        public void setName(String name) {
            this.name = name;
        }
    }

6.3 衍生注解

为了更好的进行分层,Spring可以使用其它三个注解,功能与@Component一样。写上这些注解,就相当于将这个类交给Spring管理装配了。

@Component三个衍生注解:

  • @Controller:web层

  • @Service:service层

  • @Repository:dao层

6.4 自动装配注解

参见5.2自动装配方法之方式三使用注解装配。

6.5 作用域

@scope

  • singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂,所有的对象都会销毁;

  • prototype:多例模式。关闭工厂,所有的对象不会销毁。内部的垃圾回收机制会回收。

    @Component("user")
    @Scope("prototype")
    public class User {
        @Value("Kyla")
        public String name;
    }

6.6 小结

XML与注解比较

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

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

xml与注解整合开发 :推荐

  • 使用xml管理Bean;

  • 使用注解完成属性注入;

  • 使用过程中,可以不用扫描,扫描是为了类上的注解。

7. Spring配置 - 基于Java的配置

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

  1. 实体类(省略get、set和toString方法)

    @Component      // 将这个类标注为Spring的一个组件,放到容器中
    public class User {
        @Value("Kyla")
        public String name;
    }
  2. 配置类

    @Configuration      // 代表这是一个配置类
    @ComponentScan("com.wang.pojo")        // 指定注解扫描包
    public class MyConfig01 {
        @Bean           // 通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id
        public User user(){
            return new User();
        }
    }
  3. 测试

    @Test
    public void testAppConfig(){
        // 基于java的方式配置Spring时,通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig01.class);
        User user = context.getBean("user", User.class);
        System.out.println(user.name);
    }

与基于xml的配置方式中import标签对应,基于java的配置方式也可以导入其它配置类。

  1. 其它配置类

    @Configuration
    public class MyConfig02 {
    }
  2. 导入其它配置类

    @Configuration
    @Import(MyConfig02.class)       // 导入配置类MyConfig02
    public class MyConfig01 {
        @Bean
        public User user(){
            return new User();
        }
    }

8. AOP

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

AOP再Spring中的作用:提供声明式事务;允许用户自定义切面。

名词解释:

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

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

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

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

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

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

连接点(JointPoint):与切入点匹配的执行点。

Spring的AOP就是将公共的业务 (日志 , 安全等) 和领域业务结合起来,当执行领域业务时,将会把公共业务加进来,实现公共业务的重复利用。这样,领域业务更纯粹,程序猿可以专注领域业务,其本质还是动态代理。AOP在不改变原有代码的情况下,去增加新的功能,实现方式有三种。

使用AOP织入,需要导入一个依赖包:

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
</dependency>

方式一:使用Spring实现AOP

  1. 编写业务接口(抽象角色)

    public interface UserService {
        void add();
        void delete();
        void update();
        void select();
    }
  2. 编写业务实现类(真实角色)

    public class UserServiceImpl implements UserService{
        public void add() {
            System.out.println("添加");
        }
    
        public void delete() {
            System.out.println("删除");
        }
    
        public void update() {
            System.out.println("更新");
        }
    
        public void select() {
            System.out.println("查询");
        }
    }
  3. 编写增强类(代理角色)

    // 前置增强类
    public class BeforeLog implements MethodBeforeAdvice {
        // method: 要执行的目标对象的方法
        // objects: 被调用的方法的参数(动态代理中的args)
        // o: 目标对象(动态代理中的target)
        public void before(Method method, Object[] objects, Object o) throws Throwable {
            System.out.println("[Before] " + o.getClass().getName() + " -> " + method.getName());
        }
    }
    // 后置增强类
    public class AfterLog implements AfterReturningAdvice {
        // o: 返回值
        // method: 要执行的目标对象的方法
        // objects: 被调用的方法的参数(动态代理中的args)
        // o1: 目标对象(动态代理中的target)
        public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
            System.out.println("[After] " + o1.getClass().getName() + " -> " + method.getName());
        }
    }
  4. 再spring文件中导入AOP约束,注册bean并实现AOP切入

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">
        <!-- 注册bean -->
        <bean id="userService" class="com.wang.service.UserServiceImpl"/>
        <bean id="beforeLog" class="com.wang.log.BeforeLog"/>
        <bean id="afterLog" class="com.wang.log.AfterLog"/>
    
        <!-- AOP配置 -->
        <aop:config>
            <!-- 切入点 expression: 表达式匹配要执行的方法 -->
            <aop:pointcut id="pointcut" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/>
            <!-- 执行环绕 advice-ref: 执行方法 pointcut-ref: 切入点 -->
            <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        </aop:config>
    </beans>
  5. 测试

    @Test
    public void testAopBySpring(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
    // 结果
    [Before] com.wang.service.UserServiceImpl -> add
    添加
    [After] com.wang.service.UserServiceImpl -> add

方式二:使用自定义类实现AOP

  1. 业务接口和业务实现类同上

  2. 编写自定义切入类

    public class MyPointCut {
        public void before(){
            System.out.println("[Before]");
        }
    
        public void after(){
            System.out.println("[After]");
        }
    }
  3. 再spring文件中实现AOP切入

    <!-- 注册bean -->
    <bean id="userService" class="com.wang.service.UserServiceImpl"/>
    <!-- 方式二:自定义切入类 -->
    <bean id="myPointCut" class="com.wang.myaop.MyPointCut"/>
    <aop:config>
        <!-- 自定义切面 ref: 要引用的切入类 -->
        <aop:aspect ref="myPointCut">
            <!-- 切入点 -->
            <aop:pointcut id="point" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/>
            <!-- 通知 -->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
  4. 测试

    @Test
    public void testAopByCustom(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
    // 结果
    [Before]
    添加
    [After]

方式三:使用注解实现AOP

  1. 业务接口和业务实现类同上

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

    @Aspect     // 标注这是一个切面类
    public class AnnotationPointCut {
        @Before("execution(* com.wang.service.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("[Before]");
        }
    
        @After("execution(* com.wang.service.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("[After]");
        }
    
        @Around("execution(* com.wang.service.UserServiceImpl.*(..))")
        public void around(ProceedingJoinPoint joinPoint) throws Throwable {
            System.out.println("== Before Around ==");
            System.out.println("Signature: " + joinPoint.getSignature());
            Object proceed = joinPoint.proceed();
            System.out.println(proceed);
            System.out.println("== After Around ==");
        }
    }
  3. 在Spring配置文件中注册增强类的bean,并增加支持注解的配置

    <!-- 注册bean -->
    <bean id="userService" class="com.wang.service.UserServiceImpl"/>
    <!-- 方式三:使用注解 -->
    <bean id="annotationPointCut" class="com.wang.annotation.AnnotationPointCut"/>
    <!-- 开启直接支持 -->
    <aop:aspectj-autoproxy/>
  4. 测试

    @Test
    public void testAopByAnnotation(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
    // 结果
    == Before Around ==
    Signature: void com.wang.service.UserService.add()
    [Before]
    添加
    [After]
    null
    == After Around ==

AOP参考链接:https://blog.csdn.net/qq_33369905/article/details/105828920

9. 整合MyBatis

依赖包:

<dependencies>
    <!-- junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>
    <!-- mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <!-- spring相关 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.4</version>
    </dependency>
    <!-- AOP织入 -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>
    <!-- mybatis-spring整合包(重要) -->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
</dependencies>

配置Maven静态资源过滤:

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

mybatis编程步骤:

  1. 编写实体类

  2. 编写核心配置文件

  3. 编写接口

  4. 编写mapper.xml

  5. 测试

使用MyBatis-Spring 将 MyBatis 代码无缝地整合到 Spring 中。

Spring整合MyBatis方式一

在接口实现类中使用SqlSessionTemplate类显式地声明sqlSession,并注入SqlSessionTemplate,然后注入SqlSessionFactory。

  1. 编写实体类(User.java)

    package com.wang.pojo;
    
    public class User {
        private int id;
        private String name;
        private String pwd;
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
                    '}';
        }
    }
  2. 编写mybatis核心配置文件mybatis-config.xml(也可以在spring文件中配置)

    <?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>
        <typeAliases>
            <package name="com.wang.pojo"/>
        </typeAliases>
    </configuration>
  3. 编写接口(UserMapper.java)

    public interface UserMapper {
        List<User> selectUser();
    }
  4. 编写mapper.xml文件(UserMapper.xml)

    <?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">
    
    <!--namespace绑定一个Dao/Mapper接口,相当于接口的实现类-->
    <mapper namespace="com.wang.mapper.UserMapper">
        <select id="selectUser" resultType="user">
            select * from mybatis.user
        </select>
    </mapper>
  5. 编写接口实现类(UserMapperImpl.java)

    public class UserMapperImpl implements UserMapper{
        // sqlSession不用我们自己创建了,Spring来管理
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
  6. 编写mybatis配置相关的spring文件(spring-dao.xml)

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
        <!-- 配置数据源:数据源有非常多,可以使用第三方的,也可使使用Spring的 -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
    
        <!-- 配置SqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- 绑定MyBatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:com/wang/mapper/*.xml"/>
        </bean>
    
        <!-- 注册sqlSessionTemplate,关联sqlSessionFactory -->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <!-- 无set方法,利用构造器注入 -->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    </beans>
  7. 编写总的spring文件用于bean的注入(applicationContext.xml),导入spring-dao.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
        <import resource="spring-dao.xml"/>
    
        <bean id="userMapper" class="com.wang.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    </beans>
  8. 测试

    @Test
    public void testMybatisSpring(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user.toString());
        }
    }
    // 结果
    User{id=1, name='Alice', pwd='123456'}
    User{id=2, name='Bob', pwd='abcdef'}
    User{id=3, name='Tony', pwd='987654'}
    User{id=4, name='Timi', pwd='123123'}

Spring整合MyBatis方式二

接口实现类继承SqlSessionDaoSupport,该类中已经声明了SqlSession,因此在实现类中我们通过getSqlSession() 获得SqlSession,然后直接注入SqlSessionFactory。

相对于方式一,做以下修改:

  1. 接口实现类(UserMapperImpl2.java):继承SqlSessionDaoSupport

    public class UserMapperImpl02 extends SqlSessionDaoSupport implements UserMapper {
    
        public List<User> selectUser() {
            return getSqlSession().getMapper(UserMapper.class).selectUser();
        }
    }
  2. mybatis配置相关的spring文件(spring-dao.xml):无需注册sqlSessionTemplate和关联sqlSessionFactory

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
        <!-- 配置数据源:数据源有非常多,可以使用第三方的,也可使使用Spring的 -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
    
        <!-- 配置SqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- 绑定MyBatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:com/wang/mapper/*.xml"/>
        </bean>
    </beans>
  3. 总的spring文件用于bean的注入(applicationContext.xml)

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
        <import resource="spring-dao.xml"/>
    
        <bean id="userMapper02" class="com.wang.mapper.UserMapperImpl02">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
    </beans>
  4. 测试

    @Test
    public void testMybatisSpring02(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper02", UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user.toString());
        }
    }

10. 声明式事务

  1. 使用Spring整合MyBatis的项目

  2. 在接口(UserMapper.java)中添加两个方法

    public interface UserMapper {
        List<User> selectUser();
        int addUser(User user);
        int deleteUser(int id);
    }
  3. 在mapper文件中故意把 delete语句写错,以造成事务执行失败

    <mapper namespace="com.wang.mapper.UserMapper">
        <select id="selectUser" resultType="user">
            select * from mybatis.user;
        </select>
        <insert id="addUser" parameterType="user">
            insert into mybatis.user (id, name, pwd) VALUES (#{id}, #{name}, #{pwd});
        </insert>
        <delete id="deleteUser" parameterType="_int">
            /*错误的delete语句*/
            deletes from mybatis.user where id=#{id};
        </delete>
    </mapper>
  4. 编写接口实现类(UserMapperImpl.java)

    public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
        public List<User> selectUser() {
            User user = new User(5, "Cooky", "970901");
            UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
            mapper.addUser(user);
            mapper.deleteUser(5);
            return mapper.selectUser();
        }
    
        public int addUser(User user) {
            UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
            return mapper.addUser(user);
        }
    
        public int deleteUser(int id) {
            UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
            return mapper.deleteUser(id);
        }
    }
  5. 测试

    @Test
    public void testTransaction(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapperImpl.class);
        userMapper.selectUser();
    }
    // 结果:selectUser方法中addUser方法执行成功,deleteUser方法执行失败,此事务理应也执行失败,但是结果显示插入的user已经插入成功,这不符合事务的ACID原则

Spring中的事务管理

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

编程式事务管理:将事务管理代码嵌到业务方法中来控制事务的提交和回滚

缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码

声明式事务管理:将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。

将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。

  1. 在spring文件中导入事务依赖

    xmlns:tx="http://www.springframework.org/schema/tx"
    
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
  2. 配置声明式事务

    <!-- 配置声明式事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
  3. 配置事务通知

    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
  4. 配置AOP(注意导入AOP依赖)

    <!-- 配置事务切入 -->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.wang.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
  5. 测试:此时delete语句执行失败,导致整个事务执行失败,addUser方法插入无效!

spring事务传播特性

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

propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。

propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。

propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。

propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。

propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。

propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作

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

假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。

就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!

附:狂神b站视频链接

posted @ 2021-04-03 14:00  甜了酒了果  阅读(57)  评论(0编辑  收藏  举报