Spring快速入门(多例子)

1、Spring简介

1.1、简介

  • spring:春天 —> 给软件行业带来了春天

  • 2002:首次推出Spring框架的雏形:interface21框架

  • 2004年3月24日:以interface为基础,发布了1.0正式版。

  • Rod Johnson:Spring Framework创始人,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。

  • Spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架

  • SSH:Struct2+Spring+Hibernate
    SSM:SpringMvc+Spring+Mybatis

  • 官网:https://docs.spring.io/spring-framework/docs/current/reference/html/index.html
    官方文档下载地址:https://repo.spring.io/release/org/springframework/spring/
    github地址:https://github.com/spring-projects/spring-framework

  • 导包:

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

1.2、Spring的优点

  • Spring是一个开源的免费的框架(容器)
  • Spring是一个轻量级的,非入侵式的框架
  • 控制反转(IOC),面向切面编程(AOP)
  • 支持事物的处理,对框架整合的支持

总结:Spring就是一个轻量的控制反转(IOC)和面向切面编程(AOP)的框架

2、Spring的组成及拓展

在这里插入图片描述

  • Spring官网介绍:现代化的Java开发,说白就是基于Spring的开发
    在这里插入图片描述

  • Spring Boot:

    • 一个快速开发的脚手架
    • 基于SpringBoot可以快速地开发单个微服务
    • 约定大于配置
  • Spring Cloud

    • SpringCloud是基于SpringBoot实现的
  • 现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC,相当于承上启下

  • Spring的弊端:发展太久后,违背了原来的理念,配置十分繁琐,人称“配置地狱”

3、IOC控制反转

3.1、IOC(Inversion of control)理论推导

  • 原来写业务的步骤

    1. UserDao 接口
    2. UserDaoImpl 实现类
    3. UserService 业务接口
    4. UserServiceImpl 业务实现类
  • 在我们之前的业务中,用户的需要可能会影响我们原来的代码。我们需要根据用户的需求去修改源代码!如果程序的代码量十分大,修改一次的成本代价十分昂贵
    在这里插入图片描述

  • 现在我们使用一个Set接口,已经发生了革命性的变化

    //service层的代码
    private UserDao userDao;
    //利用set动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    
    • 之前,程序主动创建对象!控制权在程序员手上;使用set注入后,程序不再具有主动性,而是变成了被动地接受对象
    • 这种思想,从本质上解决了问题,程序员不用再去管理对象的创建,系统的耦合性大大降低,可以更加专注在业务的实现上。这是IOC的原型
      在这里插入图片描述

3.2、IOC本质

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

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

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

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

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

4、HelloSpring

4.1、第一个Spring项目

  • 步骤:

    • 导包:

      <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.3.5</version>
      </dependency>
      
    • 编写Hello实体类

      public class Hello {
          private String str;
          @Override
          public String toString() {
              return "Hello{" +
                      "str='" + str + '\'' +
                      '}';
          }
          public String getStr() {
              return str;
          }
          //set方法必须有,因为Spring需要利用它来进行注入
          public void setStr(String str) {
              this.str = str;
          }
      }
      
    • 编写Spring文件,这里命名为beans.xml(下面是两个不同Module的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="..." class="...">  
              <!-- collaborators and configuration for this bean go here -->
          </bean>
          
          <bean id="..." class="...">
              <!-- collaborators and configuration for this bean go here -->
          </bean>
      
          <!-- more bean definitions go here -->
      
      </beans>
      <!--
        		使用Spring来创建对象,在Spring这些都称为Bean
              bean      对象,这个标签相当于new Hello()
                id        变量名
                class     new的对象的全路径
                property  相当于给对象中的属性设置一个值
        -->
      
        <?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="mysqlImpl" class="com.xue.dao.UserDaoMysqlImpl"/>
            <bean id="impl" class="com.xue.dao.UserDaoImpl"/>
            <bean id="userServiceImpl" class="com.xue.service.UserServiceImpl">
                <!--
                    ref:引用Spring中创建好的对象
                    value:具体的值,基本数据类型
                -->
                <property name="userDao" ref="mysqlImpl"/>
            </bean>
        
        </beans>
      
    • 测试:

      public static void main(String[] args) {
          //context:获取Spring的上下文对象
          //读取配置文件:ClassPathXmlApplicationContext:参数是配置文件的地址,可以有多个
          ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
          //我们的对象都在Spring中管理了,我们需要使用,直接去里面取出来就可以
          Hello hello = (Hello) context.getBean("hello");
          System.out.println(hello.toString());
      }
      

4.2、控制反转

  • 这个过程就叫控制反转:
    • 控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用 Spring后,对象是由 Spring来创建的
    • 反转:程序本身不创建对象,而变成被动的接收对象
    • 依赖注入:就是利用set方法来进行注入的
    • IOC是一种编程思想,由主动的编程变成被动的接收
    • 可以通过 new ClassPathXmlApplicationContext去浏览一下底层源码
  • OK,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在Xm配置文件中进行修改,所谓的IOC一句话搞定:对象由 Spring来创建,管理,装配!

5、IOC创建对象的方式

  1. 默认使用无参构造创建对象(没有无参构造会报错)

    • <bean id="user" class="com.xue.pojo.User">
          <property name="name" value="李华"/>
      </bean>
      
  2. 假设要使用有参构造创建对象:3种方式

    • 第一种:下标赋值

      <bean id="exampleBean" class="com.xue.pojo.User">
          <constructor-arg index="0" value="张三"/>
      </bean>
      
    • 第二种:通过类型创建对象(不建议使用,当两个变量名是相同类型的时候无法使用)

      <bean id="user" class="com.xue.pojo.User">
          <!--引用类型String必须用全限定名-->
          <constructor-arg type="java.lang.String" value="张三"/>
      </bean>
      
    • 第三种:直接通过参数名设置

      <bean id="user" class="com.xue.pojo.User">
          <constructor-arg name="name" value="张三"/>
      </bean>
      

6、Spring的基本配置

6.1、别名

  • 如果添加了别名,我们也可以使用别名获取到这个对象

    <bean id="user" class="com.xue.pojo.User">
        <constructor-arg name="name" value="张三"/>
    </bean>
    <alias name="user" alias="userAli"/>
    

6.2、Bean的配置

  • id:bean的唯一标识符,也就相当于对象名

  • class:bean对象所对应的全限定名:包名 + 类型名

  • name:也是别名,而且name可以取多个别名;并且空格,逗号,分号都可以进行分割

  • <bean id="userT" class="com.xue.pojo.UserT" name="userT2 u2,u3;u4">
        <property name="name" value="王五"/>
    </bean>
    

6.3、import

  • 这个import一般用于团队开发,他可以将多个配置文件导入合并成一个

  • <import resource="beans.xml"/>
    
  • 像上面那样就可以将bean.xml合并到applicationContext.xml中,这样通过applicationContext.xml就可以直接使用已导入的bean.xml

7、DI(依赖注入)

在Spring中依赖注入主要有三种方式:

7.1、构造器注入

  • 前面已经说过

7.2、Set方式注入【重点】

  • 依赖注入:Set注入!

    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象的所有属性,由容器来注入
  • 环境搭建(省略getter和setter)

    • 复杂类型

      public class Address {
          private String 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; //null注入
          private Properties info;
      }
      
    • 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 name="student" class="com.xue.pojo.Student">
              <!--第一种:普通值注入:value-->
              <property name="name" value="张三"/>
              <!--第二种:Bean注入,ref-->
              <property name="address" ref="address"/>
            <!--第三种:数组注入-->
              <property name="books">
                <array>
                      <value>红楼梦</value>
                      <value>水浒传</value>
                      <value>西游记</value>
                      <value>三国演义</value>
                  </array>
            </property>
              <!--第四种:List-->
              <property name="hobbys">
                  <list>
                      <value>听歌</value>
                      <value>看电影</value>
                      <value>烫头</value>
                  </list>
              </property>
              <!--第五种:Map-->
              <property name="card">
                  <map>
                      <entry key="身份证" value="1234567890"/>
                      <entry key="银行卡" value="3234565467568756"/>
                  </map>
              </property>
              <!--第六种:Set-->
              <property name="games">
                  <set>
                      <value>LOL</value>
                      <value>COC</value>
                      <value>AOA</value>
                  </set>
              </property>
              <!--第七种:NULL-->
              <property name="wife">
                  <null/>
              </property>
              <!--第九种:Properties:key=value-->
              <property name="info">
                  <props>
                      <prop key="学号">20190525</prop>
                      <prop key="性别"></prop>
                  </props>
              </property>
          </bean>
      
          <bean name="address" class="com.xue.pojo.Address">
              <property name="address" value="广州"/>
          </bean>
      
      </beans>
      
    • 测试

      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
      Student student = (Student) context.getBean("student");
      System.out.println(student.toString());
      

7.3、拓展方式注入

7.3.1、P命名空间注入

  • 对应的是Set方式注入

    • 测试对象

      public class User {
          private String name;
          private int age;
      }
      
    • user.xml

      <beans xmlns="http://www.springframework.org/schema/beans"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xmlns:p="http://www.springframework.org/schema/p"
                     xmlns:c="http://www.springframework.org/schema/c"
                     xsi:schemaLocation="http://www.springframework.org/schema/beans
              https://www.springframework.org/schema/beans/spring-beans.xsd">
      
      	<!--p命名空间注入:可以直接注入属性的值:property;建议只在属性简单的时候使用-->
          <bean id="user" class="com.xue.pojo.User" p:name="zhangsan" p:age="12"/>
      
          <!--c命名空间注入:通过构造器注入用:construct-->
        <bean id="user2" class="com.xue.pojo.User" c:name="李四" c:age="13"/>
      
      
      </beans>
      
    • 测试

      @Test
      public void wodeTest(){
         ApplicationContext context = new ClassPathXmlApplicationContext("user.xml");
          User user = context.getBean("user", User.class);//显式声明类型后就不需要强转
          System.out.println(user);
      }
      

7.3.2、C命名空间注入

  • 对应的是构造器方式注入

    • 测试对象

      public class User {
          private String name;
        private int age;
      }
      
    • user.xml

      <beans xmlns="http://www.springframework.org/schema/beans"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xmlns:p="http://www.springframework.org/schema/p"
                     xmlns:c="http://www.springframework.org/schema/c"
                     xsi:schemaLocation="http://www.springframework.org/schema/beans
              https://www.springframework.org/schema/beans/spring-beans.xsd">
      
          <!--c命名空间注入:通过构造器注入用:construct-->
          <bean id="user2" class="com.xue.pojo.User" c:name="李四" c:age="13"/>
      
      </beans>
      
    • 测试

      @Test
      public void wodeTest(){
         ApplicationContext context = new ClassPathXmlApplicationContext("user.xml");
          User user = context.getBean("user2", User.class);//显式声明类型后就不需要强转
          System.out.println(user);
      }
      

7.3.3、官方解释

  • 注意点:p命名和c命名空间不能直接使用,需要导入xml约束

  • P命名空间

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean name="john-classic" class="com.example.Person">
            <property name="name" value="John Doe"/>
            <property name="spouse" ref="jane"/>
        </bean>
    
        <bean name="john-modern"
            class="com.example.Person"
            p:name="John Doe"
            p:spouse-ref="jane"/>
    
        <bean name="jane" class="com.example.Person">
            <property name="name" value="Jane Doe"/>
        </bean>
    </beans>
    
  • C命名空间

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:c="http://www.springframework.org/schema/c"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="beanTwo" class="x.y.ThingTwo"/>
        <bean id="beanThree" class="x.y.ThingThree"/>
    
        <!-- traditional declaration with optional argument names -->
        <bean id="beanOne" class="x.y.ThingOne">
            <constructor-arg name="thingTwo" ref="beanTwo"/>
            <constructor-arg name="thingThree" ref="beanThree"/>
            <constructor-arg name="email" value="something@somewhere.com"/>
        </bean>
    
        <!-- c-namespace declaration with argument names -->
        <bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo"
            c:thingThree-ref="beanThree" c:email="something@somewhere.com"/>
    
    </beans>
    

8、Bean的作用域

  • ScopeDescription
    singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
    prototypeScopes a single bean definition to any number of object instances.
    requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
    sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
    applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
    websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
  • The Singleton Scope(单例模式)

    • <bean id="accountService" class="com.something.DefaultAccountService"/>
      
      <!-- the following is equivalent, though redundant (singleton scope is the default) -->
      <bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
      

      在这里插入图片描述

  • The Prototype Scope(原型模式)

    • 每一次从容器中get的时候产生不同的新的对象

    • <bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
      

      在这里插入图片描述

  • 其余的request、session、application只能在web开发中使用到

9、Bean的自动装配

自动装配是Spring满足bean依赖的一种方式

Spring会在上下文中自动寻找,并自动给bean装配属性

在Spring中有三种装配方式

9.1、在xml中显式的装配

  • <property name="name" value="张三"/>
    

9.2、在Java中显式配置

  • 后面会讲到

9.3、隐式的自动装配【重点】

9.3.1、环境搭建

  • 实体类

    public class Cat {
        public void shout(){
            System.out.println("miao~");
        }
    }
    
    public class Dog {
        public void shout(){
            System.out.println("wang!");
        }
    }
    
    public class Person {
        private String name;
        private Dog dog;
        private Cat cat;
    }
    
  • 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.xue.pojo.Cat"/>
        <bean id="dog" class="com.xue.pojo.Dog"/>
        <bean id="person" class="com.xue.pojo.Person">
            <property name="name" value="张三"/>
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
        </bean>
    
    </beans>
    
  • 测试

9.3.2、ByName自动装配

  • byName:需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致

  • <?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.xue.pojo.Cat"/>
        <bean id="dog" class="com.xue.pojo.Dog"/>
    
    <!--
       byName:会自动在容器额上下文中寻找,和自己的对象set方法后面的值对应的beanid!
               例如setDog22(Dog dog){},这里的id就应该为dog22
    -->
        <bean id="person" class="com.xue.pojo.Person" autowire="byName">
            <property name="name" value="张三"/>
        </bean>
    
    </beans>
    

9.3.3、ByType自动装配

  • byType:需要保证所有的bean的class唯一,并且这个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
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="cat" class="com.xue.pojo.Cat"/>
        <bean id="dog" class="com.xue.pojo.Dog"/>
    
    <!--
        byType:会自动在容器额上下文中寻找,和自己的对象属性类型相同的bean!
    	缺点:不能有重复的类型
    -->
        <bean id="person" class="com.xue.pojo.Person" autowire="byType">
            <property name="name" value="张三"/>
        </bean>
    
    </beans>
    

9.3.4、使用注解实现自动装配

  • JDK1.5支持注解,Spring2.5支持注解

  • The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

  • 要使用注解需要注意以下事项:

    • 导入约束:context约束

    • 配置注解的支持:< context:annotation-config/ >

    • <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns: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(常用)

    • 直接在属性上使用即可,也可以在set方式上使用

    • @Autowired在当注入在IOC容器中该类型只有一个时,通过byType进行装配;当注入容器存在多个同一类型的对象时,就是根据byName进行装配

    • 默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false。

    • 如果@Autowired自动的环境比较复杂,自动装配无法通过一个注解 [@Autowired] 完成的时候,可以使用 @Qualifier(value=“XXX”) 来配合@Autowired的使用,指定一个唯一的bean对象注入

    • 使用示例:

      • Person.java

        public class Person {
            private String name;
            @Autowired
            private Dog dog;
            @Autowired
            @Qualifier("cat2")  //指定一个唯一的bean对象注入
            private Cat cat;
        }
        
      • 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:annotation-config/>
            <bean id="cat1" class="com.xue.pojo.Cat"/>
        	<bean id="cat2" class="com.xue.pojo.Cat"/>
        	<bean id="cat" class="com.xue.pojo.Cat"/>
        	<bean id="dog" class="com.xue.pojo.Dog"/>
        	<bean id="person" class="com.xue.pojo.Person"/>
        </beans>
        
  • @Resource注解

    • 默认通过反射机制使用byName自动注入策略。

    • 最好是将@Resource放在setter方法上,因为这样更符合面向对象的思想,通过set、get去操作属性,而不是直接去操作属性

    • @Resource有name和type两个属性,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。

    • 使用示例

      public class Person {
          private String name;
          @Resource
          private Dog dog;
          @Resource(name = "cat1")
          private Cat cat;
      }
      

10、Spring注解开发

  • 在Spring4之后,要使用注解开发,必须保证aop的包被导入了
  • 使用注解需要导入context约束,增加注解的支持

10.1、bean

  • @Component:组件,放在类上,说明这个类被Spring管理了,就是bean,这时id默认是类首字母小写

    • //相当于<bean id="user" class="com.xue.pojo.User"/>
      //Component:组件
      @Component
      public class User {
          private String name="小黄";
      }
      

10.2、属性如何注入

  • @Value:可以放在set方法或者属性

    • public class User {
          //相当于<property name="name" value="小绿"/>
          @Value("小绿")
          private String name;
      }
      

10.3、衍生的注解

  • @Component有几个衍生注解,我们在web开发中,会按照MVC三层架构分层

    • dao【@Response】
    • sevice【@Service】
    • controller【@Controller】

    这四个注解功能是一样的,都是代表将某个类注册到Spring中,装配Bean

10.4、自动装配

  • @Autowired

    • @Qualifier:和@Autowired搭配使用
  • @Resource

10.5、作用域

  • @Scope:配置bean的作用域

  • @Scope("singleton")
    public class User {
        private String name;
    }
    

10.6、注解开发实例

  • 我们现在完全不使用Spring的xml配置,全权交给Java来做

  • JavaConfig原来是Spring的一个子项目,在Spring4之后成为了一个核心功能

  • 这种纯Java的配置方式,在SpringBoot中随处可见

  • 示例:

    • 实体类

      //这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
      @Component
      public class User {
          private String name;
      
          public String getName() {
              return name;
          }
      
          @Value("张三")
          public void setName(String name) {
              this.name = name;
          }
      
          @Override
          public String toString() {
              return "User{" +
                      "name='" + name + '\'' +
                      '}';
          }
      }
      
    • 配置文件

      //这个也会被Spring容器托管,注册到容器中,因为他本身也是一个@Component
      //@Configuration代表着是一个配置类,和之前看的beans.xml一样
      @Configuration
      @ComponentScan("com.xue.pojo")
      //引用配置类的class对象
      @Import(MyConfig2.class)
      public class MyConfig {
          //注册一个bean,就相当于之前写的一个bean标签
          //这个方法的名字,就相当于bean标签中的id属性
          //这个方法的返回值,就相当于bean标签中的class属性
          @Bean
          public User getUser(){
              return new User();//就是返回要注入到bean的对象
          }
      }
      
    • 测试类

      public static void main(String[] args) {
          //如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载
          ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
          User user = (User) context.getBean("getUser");
          System.out.println(user.getName());
      }
      

10.7、小结

  • xml与注解
    • xml更加万能,适用于任何场合,维护更加简单方便
    • 注解:不是自己的对象使用不了,维护相对复杂
  • 最佳实践:
    • xml用来管理bean
    • 注解只负责完成属性的注入
    • 在使用的过程中,需要注意:要使注解生效,就需要开启注解的支持

11、代理模式

  • 为什么要学代理模式?因为这就是SpringAOP的底层【SpringAOP和SpringMVC】
  • 代理模式的分类
    • 静态代理
    • 动态代理
      在这里插入图片描述

11.1、静态代理

  • 角色分析:

    • 抽象角色:一般会使用接口或者抽象类来解决
    • 真实角色:被代理的角色
    • 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
    • 客户:访问代理对象的人
  • 代码步骤:

    1. 接口

      //租房
      public interface Rent {
          public void rent();
      }
      
    2. 真实角色

      //房东
      public class Host implements Rent{
          public void rent() {
              System.out.println("房东要出租房子");
          }
      }
      
    3. 代理角色

      public class Proxy implements Rent{
          private Host host;
      
          public Proxy(Host host) {
              this.host = host;
          }
      
          public Proxy() {
          }
      
          public void rent() {
              seeHouse();
              host.rent();
              fare();
              contract();
          }
      
          //看房
          public void seeHouse(){
              System.out.println("中介带看房");
          }
      
          //收中介费
          public void fare(){
              System.out.println("收中介费");
          }
      
          //签合同
          public void contract(){
              System.out.println("签合同!");
          }
      }
      
    4. 客户端访问代理角色

      public class Client {
          public static void main(String[] args) {
              //房东要租房子
              Host host = new Host();
              //代理,中介帮房东租房子,代理角色会有一些附属操作
              Proxy proxy = new Proxy(host);
              //租客不用面对房东,直接找中介租房
              proxy.rent();
          }
      }
      
  • 代理模式的好处:

    • 可以使真实角色的操作更加纯粹!不用去关注一些公共业务
    • 公共业务就交给代理角色,实现了业务的分工
    • 公共业务发生拓展时,方便集中管理
  • 缺点:

    • 一个真实角色就会产生一个代理角色;代码量会翻倍,开发效率会变低
  • AOP
    在这里插入图片描述

11.2、动态代理

  • 动态代理和静态代理一样

  • 动态代理类是动态生成的,不是直接写好的

  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理

    • 基于接口 — JDK的动态代理
    • 基于类的 — cglib
    • Java字节码实现:JAVAssist
  • 动态代理的好处:

    • 可以使真实角色的操作更加纯粹!不用去关注一些公共业务
    • 公共业务就交给代理角色,实现了业务的分工
    • 公共业务发生拓展时,方便集中管理
    • 一个动态代理类代理的是一个接口,一般就是对应的一类业务
    • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
  • 基于接口 — JDK的动态代理

    • 需要了解两个类:Proxy:用于生成得到代理类实例、InvocationHandler:调用处理程序,并返回一个结果

    • 示例:

      • 接口

        public interface UserService {
            public void add();
            public void delete();
            public void update();
            public void query();
        }
        
      • 真实角色

        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 query() {
                System.out.println("查询了一个用户");
            }
        }
        
      • ProxyInvocationHandler.java

        //使用这个类自动生成代理类
        //ProxyInvocationHandler主要做两件事情:
        // 1、invoke执行真正要执行的方法
        // 2、得到代理类:调用set得到要代理的角色(setRent);获得代理类(getProxy)
        public class ProxyInvocationHandler implements InvocationHandler {
        
            //被代理的接口
            private Object target;
            public void setTarget(Object target) {
                this.target = target;
            }
        
            //生成得到代理类实例
            public Object getProxy(){
                return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
            }
        
            //处理代理实例,并返回结果
            //Processes a method invocation on a proxy instance and returns the result.  This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with.(源码解释)
            //每个代理实例都有一个关联的调用处理程序。当在代理实例上调用某个方法时,将对该方法的位置进行编码并发送到其调用处理程序的invoke方法
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                log(method.getName());
                //动态代理的本质就是使用反射机制实现
                Object result = method.invoke(target, args);
                return result;
            }
        
            public void log(String msg){
                System.out.println("调用了"+msg+"方法");
            }
        }
        
      • 客户端访问代理角色

        public static void main(String[] args) {
            //真实角色,当有新的实现类的时候,直接在这里new就可以了,不用再重新写代理的模板
            UserServiceImpl userService = new UserServiceImpl();
            //代理角色,现在不存在
            ProxyInvocationHandler pih = new ProxyInvocationHandler();
            //设置要代理的对象
            pih.setTarget(userService);
            //动态生成代理类(动态代理代理的是接口)
            UserService proxy = (UserService) pih.getProxy();
            proxy.add(); //实际上就是调用invoke
        }
        

12、AOP

12.1、什么是AOP

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

在这里插入图片描述

12.2、AOP在Spring中的应用

提供声眀式事务:允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等
  • 切面( ASPECT):横切关注点被模块化的特殊对象。即,它是一个类(对应动态代理的Log)
  • 通知( Advice):切面必须要完成的工作。即,它是类中的一个方法(对应动态代理的Log中的方法)
  • 目标( Target):被通知对象
  • 代理( Proxy):向目标对象应用通知之后创建的对象
  • 切入点( PointCut):切面通知执行的“地点”的定义
  • 连接点( JoinPoint):与切入点匹配的执行点

在这里插入图片描述

  • SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice
    在这里插入图片描述

    即AOP在不改变原有代码的情况下,增加新的功能

12.3、使用Spring实现AOP

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

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

12.3.1、方式一:使用原生Spring API接口

  • 示例:

    • 接口

      public interface UserService {
          public void add();
          public void delete();
          public void update();
          public void select();
      }
      
    • 实现类

      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("查询了一个用户");
          }
      }
      
    • 切面

      //log
      public class Log implements MethodBeforeAdvice {
          //methof:要执行的目标对象的方法
          //args:参数
          //target:目标对象
          public void before(Method method, Object[] args, Object target) throws Throwable {
              //这个方法会在我们执行方法之前自动调用
              System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
          }
      }
      
      //afterLog
      public class AfterLog implements AfterReturningAdvice {
          //returnValue:执行之后可以拿到返回值
          public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
              System.out.println("执行了"+method.getName()+"方法;返回结果为"+returnValue);
          }
      }
      
    • 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"
             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.xue.service.UserServiceImpl"/>
          <bean id="log" class="com.xue.log.Log"/>
          <bean id="afterLog" class="com.xue.log.AfterLog"/>
      
          <!--配置AOP:需要导入AOP的约束-->
          <aop:config>
              <!--切入点:expression:表达式,execution(要执行的位置!修饰词,返回值,类名,方法名,参数-->
              <!--execution表达式:*:表示返回类型为所有类型   *:表示该类下的所有方法  ..:两个点表示可以有任意的参数-->
              <aop:pointcut id="pointcut" expression="execution(* com.xue.service.UserServiceImpl.*(..))"/>
      
              <!--执行环绕增加-->
              <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
              <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
          </aop:config>
      
      </beans>
      
    • 测试

      public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
          //动态代理的是接口,因此这里需要返回一个接口而不是实现类
          UserService userService = context.getBean("userService", UserService.class);
          userService.select();
      }
      

12.3.2、方式二:自定义类来实现AOP【建议】

  • 示例:

    • 接口:同上

    • 实现类:同上

    • 切面

      public class DiyPointCut {
          public void before(){
              System.out.println("==========方法执行前===========");
          }
      
          public void after(){
              System.out.println("==========方法执行后===========");
          }
      }
      
    • 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"
             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.xue.service.UserServiceImpl"/>
      
          <!--方式二:自定义类-->
          <bean id="diy" class="com.xue.diy.DiyPointCut"/>
          <aop:config>
              <!--aspect:切面-->
              <aop:aspect ref="diy">
                  <!--切入点-->
                  <aop:pointcut id="point" expression="execution(* com.xue.service.UserServiceImpl.*(..))"/>
                  <!--通知-->
                  <aop:before method="before" pointcut-ref="point"/>
                  <aop:after method="after" pointcut-ref="point"/>
              </aop:aspect>
          </aop:config>
      </beans>
      
    • 测试:同上

12.3.3、方式三:注解实现AOP

  • 接口:同上

  • 实现类:同上

  • 切面:

    @Aspect//标注这个类是一个切面
    public class AnnotationPointCut {
        @Before("execution(* com.xue.service.UserServiceImpl.*(..))")//注意别导错包:要导Aspect
        public void before(){
            System.out.println("=====执行方法前=====");
        }
    
        @After("execution(* com.xue.service.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("=====执行方法后=====");
        }
    
        @Around("execution(* com.xue.service.UserServiceImpl.*(..))")
        public void around(ProceedingJoinPoint jp) throws Throwable {
            System.out.println("环绕前");
            Signature signature = jp.getSignature();//获取签名
            System.out.println("signature:"+signature);
    
            Object proceed = jp.proceed();//执行方法
            System.out.println("环绕后");
        }
    
    }
    
  • 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"
           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.xue.service.UserServiceImpl"/>
        <!--方式三:注解-->
        <bean id="annotationPointCut" class="com.xue.diy.AnnotationPointCut"/>
        <!--开启注解支持    JDK(默认:proxy-target-class="false")   cglib(proxy-target-class="true")-->
        <aop:aspectj-autoproxy/>
    
    </beans>
    
  • 测试:同上

13、整合Mybatis

  • 步骤:

    1. 导入相关jar包

      • junit

      • mybatis

      • mysql数据库

      • spring相关

      • aop织入

      • mybatis-spring(用于整合mybatis和spring)

      • <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.5</version>
        </dependency>
        <!--Spring操作数据库的话,还需要一个spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        pendencies>
        
    2. 编写配置文件

    3. 测试

13.1、回忆Mybatis

  • 步骤:
    1. 编写实体类
    2. 编写核心配置文件
    3. 编写接口
    4. 编写Mapper.xml
    5. 测试

13.2、方式一:SqlSessionFactoryBean【重点理解】

  • 步骤:

    • 编写实体类:User

      @Data
      public class User {
          private int id;
          private String name;
          private String pwd;
      }
      
    • 编写接口:UserMapper

      public interface UserMapper {
          public List<User> selectUser();
      }
      
    • 接口实现类:UserMapperImpl【相当于service层的代码,帮助给spring创建userMapper对象】

      public class UserMapperImpl implements UserMapper{
          //“将原来操作mybatis的代码封装了起来”
      
          //在原来,我们所有的操作,都使用sqlSession来执行;现在都使用SqlSessionTemplate,并且它是线程安全的
          private SqlSessionTemplate sqlSession;
      
          public void setSqlSession(SqlSessionTemplate sqlSession) {
              this.sqlSession = sqlSession;
          }
      
          //操作原来Mybatis做的事情
          public List<User> selectUser() {
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
              return mapper.selectUser();
          }
      }
      
    • 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">
      <mapper namespace="com.xue.mapper.UserMapper">
          
          <select id="selectUser" resultType="user">
              select * from mybatis.user ;
          </select>
          
      </mapper>
      
    • Mybatis配置文件:mybatis-config.xml

      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE configuration
              PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-config.dtd">
      <!-- 核心配置文件-->
      <configuration>
      
          <!--一般在Mybatis配置文件里面留下两项:别名和设置-->
      
          <typeAliases>
              <package name="com.xue.pojo"/>
          </typeAliases>
      
      </configuration>
      
    • Spring配置文件:spring-dao.xml

      • 第一步:配置数据源
      • 第二步:SqlSessionFactory
      • 第三部:SqlSession
      <?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">
      
          <!--DataSource:使用spring的数据源替换Mybatis的配置  c3p0   dbcp   druid
              这里的class使用Spring 提供的JDBC
          -->
          <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&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配置文件,可以完全不用Mybatis配置文件,直接在这里配置-->
              <property name="configLocation" value="classpath:mybatis-config.xml"/>
              <!--注册Mapper.xml-->
              <property name="mapperLocations" value="classpath:com/xue/mapper/UserMapper.xml"/>
          </bean>
      
          <!--SqlSessionTemplate:就是我们使用的sqlSession-->
          <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
              <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
              <constructor-arg index="0" ref="sqlSessionFactory"/>
          </bean>
      
          <bean id="userMapper" class="com.xue.mapper.UserMapperImpl">
              <property name="sqlSession" ref="sqlSession"/>
          </bean>
        
      </beans>
      
    • 测试

      @Test
      public void test() throws IOException {
          ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
          UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
          for (User user : userMapper.selectUser()) {
              System.out.println(user);
        }
      }
      

13.3、方式二:SqlSessionDaoSupport

  • 步骤:

    • 编写实体类:User

    • 编写接口:UserMapper

    • 接口实现类:UserMapperImpl2

      //SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法
      public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
          public List<User> selectUser() {
              return getSqlSession().getMapper(UserMapper.class).selectUser();
          }
      }
      
    • UserMapper.xml

    • Mybatis配置文件:mybatis-config.xml

    • 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">
      
          <!--DataSource:使用spring的数据源替换Mybatis的配置  c3p0   dbcp   druid
              这里的class使用Spring 提供的JDBC
          -->
          <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&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配置文件,可以完全不用,直接在这个xml文件下配置-->
              <property name="configLocation" value="classpath:mybatis-config.xml"/>
              <!--注册Mapper.xml-->
              <property name="mapperLocations" value="classpath:com/xue/mapper/*.xml"/>
          </bean>
          
          <!--直接省略sqlSession-->
      
          <bean id="userMapper2" class="com.xue.mapper.UserMapperImpl2">
              <property name="sqlSessionFactory" ref="sqlSessionFactory" />
          </bean>
      
      </beans>
      
    • 测试

      @Test
      public void test() throws IOException {
          ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
          UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
          for (User user : userMapper.selectUser()) {
              System.out.println(user);
          }
      }
      

14、事务

14.1、回顾事务

  • 把一组业务当成一个业务来做;要么都成功,要么都失败

  • 事务在项目开发中,十分重要,涉及数据的一致性问题

  • 确保完整性和一致性

  • 事务的ACID原则

    • 原子性
    • 一致性
    • 隔离性:多个业务可能操作同一个资源,防止数据损坏
    • 持久性:事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中

14.2、spring中的事务管理

  • 声明式事务:AOP

    • 事务的传播特性:(7种,了解即可)

      • requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是Spring默认的选择
      • supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
      • mandatory:使用当前事务,如果没有当前事务,就抛出异常。
      • required_new:新建事务,如果当前存在事务,把当前事务挂起。
      • not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
      • never:以非事务方式执行操作,如果当前事务存在则抛出异常。
      • nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作。
    • 示例:

      • 在spring配置文件中需要导入tx的约束文件

        xmlns:tx="http://www.springframework.org/schema/tx"
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        
      • 在spring配置文件中配置使用事务

        <!--配置声明式事务-->
        <!--第一步:传入datasource,获得transactionManager-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <constructor-arg ref="dataSource" />
        </bean>
        <!--结合AOP实现事务的织入-->
        <!--1.配置事务通知-->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <!--给哪些方法配置事务-->
            <!--配置事务的传播特性:propagation-->
            <tx:attributes>
        		<tx:method name="addUser" propagation="REQUIRED"/>
        		<tx:method name="deleteUser" propagation="REQUIRED"/>
        		<tx:method name="update" propagation="REQUIRED"/>
        		<tx:method name="query" read-only="true"/>
        		<tx:method name="*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
        <!--2.配置事务切入-->
        <aop:config>
            <aop:pointcut id="txPointCut" expression="execution(* com.xue.mapper.*.*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
        </aop:config>
        
  • 编程式事物:需要在代码中进行事物的管理(较少用)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值