Spring学习笔记

Spring

概述

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

官网:https://spring.io/

下载地址:https://repo.spring.io/release/org/springframework/spring/

GitHub下载地址:https://github.com/spring-projects/spring-framework/releases

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

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>
<!--spring mybatis整合包-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

优点

  • spring是一个免费的开源的容器(框架)。
  • 是一个轻量级、非入侵式(引入框架不会改变代码任何情况)的框架。
  • 控制反转(IOC)。面向切面编程(AOP)。
  • 支持事务的处理,对框架整合的支持。

Spring就是一个控制反转(IOC)面向切面编程(AOP)的框架。

组成

扩展

  • 现代化的Java开发,基于Spring的开发。

  • Spring Boot
    • 一个快速开发的脚手架。
    • 基于Spring Boot可以快速开发单个微服务。
    • 约定大于配置。(按照规定做)
  • Spring Cloud
    • Spring Cloud是基于Spring Boot实现的。

大多数公司都在使用Spring Boot进行快速开发。学习Spring Boot的前提,需要完全掌握Spring、Spring MVC。

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

IOC理论推导

  1. UserDao接口
  2. UserDaoImpl实现类
  3. UserService业务接口
  4. UserServiceImpl业务实现类

在我们之前的业务中,用户的需求可能会影响原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本十分昂贵。

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

    import com.sx.dao.UserDao;
    //利用set实现动态注入值的实现
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
  • 之前程序是主动创建对象,控制权在程序员手上!
  • 使用了Set注入后,程序不再具有主动性,而实变成了被动的接受对象。

控制反转啦!

这种思想,从本质上解决了问题,程序员不用再去管理对象的创建了(new),系统的耦合性大大降低。可以更加专注的在业务的实现上。这是IOC的原型!

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

Hello Spring

  1. 创建pojo类
package com.sx.pojo;

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 + '\'' +
                '}';
    }
}

  1. 配置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> 
</beans>
 <!--使用spring来创建对象,在spring中这些都成为bean
        bean = 对象  这个标签相当于new了一个hello
        类型 变量名 = new 类型();
        Hello hello =  new Hello();

        id = 变量名
        class = new 的对象
        property 相当于给对象中的属性设置一个值
    -->
    <bean id="hello" class="com.sx.pojo.Hello">
        <property name="str" value="spring"/>
    </bean>
  1. 获取容器
//解析xml文件,生成管理相应的Bean对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//getBean获取对应bean的id
Hello hello = (Hello) context.getBean("hello");
  • Hello对象是由谁创建的?
    • 由Spring创建的。
  • Hello对象的属性值是怎么设置的?
    • hello对象的属性是由Spring容器设置的。

这个过程就叫做控制反转

  • 控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。
  • 反转:程序本身不创建对象,而变为被动的接收对象。
  • 依赖注入:利用set方法进行注入。

IOC是一种编程思想,由主动的编程变成被动的接收对象。对象由Spring进行创建,管理,装配

IOC创建对象的方式

  1. 使用无参构造创建对象,默认~

  2. 假设我们要用有参构造constructor-arg创建方法~

    • 通过下标赋值

      	<bean id="user" class="com.sx.pogo.User">
                 <constructor-arg index="0" value="狂"/>
                 <constructor-arg index="1" value="1" />
         </bean>
      
    • 通过类型赋值(不推荐)

      	<bean id="user" class="com.sx.pogo.User">
              <constructor-arg type="java.lang.String" value="sx"/>
              <constructor-arg type="int" value="2"/>
          </bean>
      
    • 通过参数名赋值

      	<bean id="user" class="com.sx.pogo.User">
              <constructor-arg name="name" value="FFF"/>
              <constructor-arg name="id" value="4"/>
          </bean>
      

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了。

Spring 配置

别名

  • 通过给bean设置别名,可以在getBean()中使用,name和alias都可以扫描到。
<alias name="user" alias="bm"/>

Bean的配置

 <!--id:bean的唯一标识符,相当于我们写的对象名
        class:bean对象所对应的全限定名
        name:也是别名,而且name可以同时取多个别名
    -->
    <bean id="user" name="user2,u2"  class="com.sx.pogo.User">
        <constructor-arg name="name" value="FFF"/>
        <constructor-arg name="id" value="4"/>
    </bean>

import

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

假设现在项目有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的。

  • applicationContext.xml
<import resource="beans2.xml"/>
<import resource="beans.xml"/>

依赖注入DI

构造器注入

前文已说明

Set注入【重点】

  • 依赖注入:Set注入!

    • 依赖:bean对象的创建依赖于容器。

    • 注入:bean对象的所有属性由容器来注入。

【环境搭建】

  1. 复杂类型
package com.sx.pojo;

public class Address {
    private String address;
}
  1. 真实测试对象
package com.sx.pojo;

import java.util.*;

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 Properties info;
    private String wifr;
  1. xml注入

    • 第一种注入(属性为基本类型/String)

        <!--第一种,普通值注入,value-->
          <bean id="student" class="com.sx.pojo.Student">
              <property name="name" value="sx"/>
          </bean>
      
    • 第二种注入(属性为引用类型)

       	<bean id="address" class="com.sx.pojo.Address">
              <property name="address" value="天津市"/>
      	</bean>
      	<bean id="student" class="com.sx.pojo.Student">
              <property name="address" ref="address"/>
          </bean>
      
    • 第三种注入(数组类型)

       	<bean id="student" class="com.sx.pojo.Student">
              <property name="books">
                  <array>
                      <value>Java</value>
                      <value>SQL</value>
                      <value>SSM</value>
                      <value>SpringBoot</value>
                  </array>
              </property>
          </bean>
      
    • 第四种注入(集合)

      	<bean id="student" class="com.sx.pojo.Student">
               <property name="hobbys">
                  <list>
                      <value>听歌</value>
                      <value>写代码</value>
                      <value>看动漫</value>
                  </list>
              </property>
          </bean>
      
    • 第五种注入(Map)

      	<bean id="student" class="com.sx.pojo.Student">	
      		<property name="card">
                  <map>
                      <entry key="身份证" value="121212121212"/>
                      <entry key="银行卡" value="412432432432423"/>
                  </map>
              </property>
       	 </bean>
      
    • 第六种注入(Set)

      	<bean id="student" class="com.sx.pojo.Student">	
      		<property name="games">
                  <set>
                     <value>lol</value>
                     <value>R6</value>
                  </set>
              </property>
       	 </bean>
      
    • 第七种注入(null)

      	<bean id="student" class="com.sx.pojo.Student">	  
      		<property name="wifr">
                  <null/>
              </property>
      	 </bean>
      
    • 第八种注入(Properties)

      	<bean id="student" class="com.sx.pojo.Student">	 <property name="info">
                  <props>
                     <prop key="学号">20200606</prop>
                     <prop key="性别">男</prop>
                  </props>
              </property>
      	</bean>
      
  2. 测试类

public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
}

拓展注入方式

我们可以使用p命名空间和c命名空间进行出入

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

  	<!--p命名空间注入,可直接注入属性的值:property-->
    <bean id="user" class="com.sx.pojo.User" p:name="sx" p:age="18"/>

    <!--p命名空间注入,通过构造器注入:constructor-arg-->
    <bean id="user2" class="com.sx.pojo.User" c:age="20" c:name="ss"/>

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

Bean的作用域

image-20200528163417801

  1. 单例模式:Spring默认机制
<bean id="user" class="com.sx.pojo.User" scope="singleton"/>
  1. 原型模式:每次从容器中get时都会产生一个新对象
<bean id="user" class="com.sx.pojo.User" scope="prototype"/>
  1. 其余的request、session、application这些只能在web开发中使用。

Bean的自动装配

  • 自动装配是Spring满足Bean依赖的一种方式。
  • Spring会在上下文中自动寻找,并自动给bean装配属性。

使用xml

在Spring中有三种装配的方式

  1. 在xml中显示配置。

  2. 在java中显示配置。

  3. 隐式的自动装配bean。【重要】

        <bean id="cat" class="com.sx.pojo.Cat" />
        <bean id="dog" class="com.sx.pojo.Dog" />
        <!--byName:会自动在容器中查找,和自己对象set方法后面的值对应的bean。
            byType:会自动在容器中查找,和自己对象类型相同的bean。(类型全局唯一)
        -->
        <bean id="people" class="com.sx.pojo.People" autowire="byType" >
            <property name="name" value="ss"/>
        </bean>
    

    小节:

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

使用注解

使用注解须知:

  1. 导入约束: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:p="http://www.springframework.org/schema/p"
           xmlns:c="http://www.springframework.org/schema/c"
           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优先根据类型判断,bean类型相同通过name判断。

  • 如果xml文件中同一个对象被多个bean使用,@Autowired无法按类型找到,可以指定用@Qualifier指定id查找。

@Qualifier(value = "beanId")

使用Qualifier来配合Autowired的使用,指定一个唯一的额Bean注入。

使用注解开发

  1. bean

  2. 属性如可注入

  3. 衍生注解

    • @Component(写在类上,代表此类已被spring管理了,就是bean了)
         <!--扫描哪些包,写完这句就可以在对应的类上加入@Component注解了-->
        <context:component-scan base-package="com.sx.pojo"/>
    
    • dao【@Repository】
    • service【@Service】
    • controller【@Controller】

    这四个注解功能是相同的,都是代表将某个类注入到Spring中,装配Bean

  4. 自动装配

    • @Autowired
  5. 作用域

    • @Scope("作用域名")
  6. 小结

    • xml与注解:
      • xml更加万能,维护极其方便。
      • 注解每个管理一个类,维护相对复杂。
      • xml用来管理bean
      • 注解负责装配bean

使用Java的方式配置Spring

现在完全不需要xml进行配置了,全部交给java来做。

JavaConfig,在Spring4之后,成为了核心功能。

  • 配置类
@Configuration  //代表这是一个spring的配置文件,和beans.xml是一样的
@ComponentScan("com.sx.pojo")//规定去扫描的包
@Import(config2.class)//引入其它配置类
public class MyConfig {
    @Bean //相当于一个bean标签 方法名就相当于id属性  方法返回值就相当于class属性
    public User user(){
        return new User();
    }
    @Bean
    public Cat cat(){
        return new Cat();
    }
    @Bean
    public Dog dog(){
        return new Dog();
    }
}
  • 实体类
public class User {

    @Value("1")
    private int id;
    @Value("sx")
    private String name;
    @Value("sx")
    private String gender;
    @Autowired
    private Dog dog;
    @Autowired
    private List<Cat> cats;
    
    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Dog getDog() {
        return dog;
    }

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

    public List<Cat> getCats() {
        return cats;
    }

    public void setCats(List<Cat> cats) {
        this.cats = cats;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", dog=" + dog +
                ", cats=" + cats +
                '}';
    }
}
  • 测试类
 public static void main(String[] args) {
        //如果完全使用了配置类的方式去做,我们就只能通过AnnotationConfigApplicationContext上下文来获取容器。
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = context.getBean("user", User.class);
    }

代理模式

为什么要学习代理模式呢?Spring AOP的底层。【Spring AOP】

代理模式分类:

静态代理

  • 角色分析:

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

    • 接口

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

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

      public class Proxy implements Rent{
      
         //房东
          private Host host;
          public Proxy(Host host) {
              this.host = host;
          }
      
          public Proxy() {
          }
      
          //代理
          public void rent() {
              seeHouse();
              host.rent();
              faer();
          }
          //看房
          public void seeHouse(){
              System.out.println("中介带你看房子");
          }
      
          //收中介费
          public void faer(){
              System.out.println("收费");
          }
      
      }
      
      
    • 客户端访问代理角色

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

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

    • 一个真实角色就会产生一个代理角色,代码量会翻倍,开发效率会变低。

动态代理

  • 下次一定~

AOP

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

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

使用Spring实现AOP

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

		<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

方式一:使用spring中的API接口

  1. 定义一个接口

    public interface UserService {
        void add();
        void delete();
        void update();
        void select();
    }
    
  2. 接口实现类

    package com.sx.service;
    
    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. 比如在程序运行时加入log,新建log包和log类,实现AfterReturningAdvice接口(后置通知)

    package com.sx.log;
    import org.springframework.aop.AfterReturningAdvice;
    import java.lang.reflect.Method;
    
    public class AfterLog implements AfterReturningAdvice {
        //method执行的方法
        //o返回结果
        //objects参数
        //o1传入的实现类
        public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
            System.out.println("执行了"+method.getName()+"返回结果为"+o1+"********");
        }
    }
    
  4. 编写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:p="http://www.springframework.org/schema/p"
           xmlns:c="http://www.springframework.org/schema/c"
           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
            http://www.springframework.org/schema/tx
            https://www.springframework.org/schema/tx/spring-tx.xsd">
    
        <!--注册bean-->
        <bean id="userService" class="com.sx.service.UserServiceImpl"/>
        <bean id="log" class="com.sx.log.Log"/>
        <bean id="afterLog" class="com.sx.log.AfterLog"/>
    
        <!--方式一:使用原生Spring API接口-->
        <!--配置aop-->
        <aop:config>
            <!--切入点:expression=""表达式,execution()要执行的位置-->
            <aop:pointcut id="pointcut" expression="execution(* com.sx.service.UserServiceImpl.*(..))"/>
            <!--执行环绕增强-->
            <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        </aop:config>
    </beans>
    
  5. 测试类

    import com.sx.service.UserService;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            //这里代理的是接口
            UserService userService = context.getBean("userService", UserService.class);
            userService.add();
        }
    }
    

方式二:使用自定义类

沿用了方法一中的接口和实现类

  1. 自定义一个切入方法

    package com.sx.diy;
    
    public class DiyPointCut {
    
        public void before(){
            System.out.println("=================方法执行前===============");
        }
        public void after(){
            System.out.println("=================方法执行后================");
        }
    }
    
  2. 编写xml文件

     <bean id="diy" class="com.sx.diy.DiyPointCut"/>
        <aop:config>
            <!--自定义切面,ref要引用的类-->
            <aop:aspect ref="diy">
                <!--切入点-->
                <aop:pointcut id="point" expression="execution(* com.sx.service.UserServiceImpl.*(..))"/>
                <!--通知-->
                <aop:before method="before" pointcut-ref="point"/>
                <aop:after method="after" pointcut-ref="point"/>
            </aop:aspect>
        </aop:config>
    
  3. 测试

MyBatis-Spring整合

  1. 所需pom.xml依赖

     <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</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.1.9.RELEASE</version>
            </dependency>
    
            <!--spring操作数据库的话需要spring-jdbc-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
    
            <!--aop织入包-->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.13</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.2</version>
            </dependency>
    
        </dependencies>
    
  2. mybatis-config.xml

    <?xml version="1.0" encoding="GBK" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--核心配置文件-->
    <configuration>
        <!--配置别名-->
        <typeAliases>
            <typeAlias type="com.sx.pojo.User" alias="user"/>
        </typeAliases>
        <!--环境-->
       <!-- <environments default="development">
            &lt;!&ndash;开发环境&ndash;&gt;
            <environment id="development">
                <transactionManager type="JDBC"/>&lt;!&ndash;事务管理&ndash;&gt;
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306?serverTimezone=GMT&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>-->
       <!-- <mappers>
           <mapper class="com.sx.mapper.UserMapper"/>
        </mappers>-->
    </configuration>
    
    • 这一步中的所有操作都可以集成至spring中
  3. spring-dao.xml

    <?xml version="1.0" encoding="GBK"?>
    <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">
        <!--1、DataSource:使用spring的数据源替换mybatis的配置-->
        <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?serverTimezone=GMT&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </bean>
    
        <!--sqlSessionFactory:spring帮我们处理sqlSessionFactory的创建-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!--绑定Mybatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <!--绑定mapper.xml-->
            <property name="mapperLocations" value="classpath:com/sx/mapper/*.xml"/>
         </bean>
    
        <!--SqlSessionTemplate就是我们使用的SqlSession,可以通过构造器注入-->
        <bean id="SqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
       <!--创建userMapper bean-->
        <bean id="userMapper" class="com.sx.mapper.UserMapperImpl">
            <property name="sqlSessionTemplate" ref="SqlSessionTemplate"/>
        </bean>
    
    </beans>
    
  4. UserMapper的实现类

    package com.sx.mapper;
    
    import com.sx.pojo.User;
    import org.mybatis.spring.SqlSessionTemplate;
    
    import java.util.List;
    
    public class UserMapperImpl implements UserMapper {
    
        //原来我们都是用sqlSession来执行
        //现在使用sqlSessionTemplate
        private SqlSessionTemplate sqlSessionTemplate;
    
        //set方法
        public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
            this.sqlSessionTemplate = sqlSessionTemplate;
        }
    
        //返回我们写的类
        public List<User> selectUser() {
            return sqlSessionTemplate.getMapper(UserMapper.class).selectUser();
        }
    }
    
  5. 测试,通过ClassPathXmlApplicationContext生成context调用mapper。

    ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
            List<User> users = userMapper.selectUser();
            System.out.println(users);
    

声明式事务

  • 把一组业务当成一个业务来做。要么都成功,要么都失败。
  • 事务在项目开发中十分重要,涉及到数据的一致性问题。
  • 确保一致性和完整性。

事务的ACID原则

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务操作同一个资源,防止数据损坏
  • 持久性

spring中的事务管理

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

    <!--结合AOP实现事务的织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性:REQUIRED默认-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.sx.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
posted @ 2020-05-30 14:40  yukinon  阅读(88)  评论(0编辑  收藏  举报