Spring5学习(kuang)

Spring

一、Spring

1.1 简介

  • Spring:春天
  • 2002年,首次推出了Spring框架的雏形:interface21框架
  • Spring框架以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日,发布了1.0正式版本
  • Rod Johnson,Spring Framework创始人
  • Spring理念:使现有的技术更加容易使用

官网:https://spring.io/projects/spring-framework

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

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

1.2 优点

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

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

1.3 Spring的组成

1.4 扩展

  • Spring Boot
    • 一个快速开发的手脚架
    • 基于SpringBoot可以快速的开发单个微服务
    • 约定大于配置!
  • Spring Cloud
    • SpringCloud 是基于SpringBoot实现的

弊端:发展了太多之后,违背了原来的理念!配置十分繁琐,人称:"配置地狱"

二、IOC理论推导

用户不同的需求可能会导致我们不断的修改源码,会存在成本问题

可以使用Set接口实现,让用户自己调用,选择

@Data
public class UserServiceImpl implements UserService {
//    private UserDao userDao = new UserDaoMysqlImpl();
    private UserDao userDao;

    public void getUser() {
        userDao.getUser();
    }
}
  • 之前,程序是主动创建对象!控制权在程序猿手上
  • 使用了Set注入,程序不再具有主动性,而是变成了被动的接受对象

这种思想,本质上解决问题!系统耦合度大大降低,可以更加专注在业务的实现上!

IOC本质

控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法

控制反转后将对象交第三方,控制反转就是:获得依赖对象的方式反转了。

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

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

三、HelloSpring

配置文件

<?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创建对象,在spring中这些都称之为bean-->
    <!--
        bean 相当于 对象                 new 对象
        id 相当于 变量名
        class 相当于 全限定
        property 相当于 给对象中的属性赋初始值
        value
    -->
    <bean id="hello" class="cn.imut.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>c

测试

public class MyTest {
    public static void main(String[] args) {
        //用xml加载必须使用(获取Spring的上下文对象)
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //我们的对象都在Spring中管理了,若要使用,直接取出即可
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}
  • Hello是由Spring创建的
  • hello对象的属性是由Spring容器设置的

这个过程称之为控制反转

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

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

依赖注入:就是利用Set方法来进行注入的。

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

四、IOC创建对象的方式

  1. 使用无参构造创建对象,默认!
  2. 若要使用有参构造

      1. 下标赋值

            <!-- 下标赋值-->
            <bean id="user" class="cn.imut.pojo.User">
                <constructor-arg index="0" value="张磊"/>
            </bean>
      2. 类型创建

            <!-- 不建议使用-->
            <bean id="user" class="cn.imut.pojo.User">
                <constructor-arg type="java.lang.String" value="张磊"/>
            </bean>
      3. 直接通过参数名设置

           <bean id="user" class="cn.imut.pojo.User">
                <constructor-arg name="name" value="张磊"/>
            </bean>

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

五、Spring配置

5.1别名

    <!-- 别名-->
    <alias name="user" alias="user2"/>

5.2 Bean的配置

    <!--
        id  : bean的唯一标识符,相当于对象名
        class : 全限定名 包名 + 类名
        name : 也是别名,name可以同时起多个别名
    -->
    <bean id="userT" class="cn.imut.pojo.User" name="user3 u2,u3;u4">
        <property name="name" value="1"/>
    </bean>

5.3 import

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

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

使用时,直接用总的配置即可

六、DI依赖注入

6.1 构造器注入

前面已经说明

6.2 Set注入[重点]

  • 依赖注入:Set注入
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入

【环境搭建】

  1. 复杂类型

    @Data
    public class Address {
        private String address;
    }
  2. 真实测试对象

    @Data
    @SuppressWarnings("all")
    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 wife;        //空指针
    }
  3. 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="cn.imut.pojo.Address">
            <property name="address" value="呼和浩特"/>
        </bean>
    
        <bean id="student" class="cn.imut.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>
                    <value>乐</value>
                </list>
            </property>
    
            <!-- 第五种,Map注入-->
            <property name="card">
                <map>
                    <entry key="身份证" value="123"/>
                    <entry key="QQ号" value="1234"/>
                </map>
            </property>
    
            <!-- 第六种,Set注入-->
            <property name="games">
                <set>
                    <value>LOL</value>
                    <value>CF</value>
                </set>
            </property>
    
            <!-- 第七种,null-->
            <property name="wife">
                <null/>
            </property>
    
            <!-- 第八种,properties-->
            <property name="info">
                <props>
                    <prop key="学号">123456</prop>
                    <prop key="姓名">张磊</prop>
                    <prop key="性别">男</prop>
                </props>
            </property>
        </bean>
    </beans>
  4. 测试类

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

6.3 拓展方式

可以使用p或者c命名空间

    <!-- p命名空间注入,可以直接注入属性-->
    <bean id="user" class="cn.imut.pojo.User" p:name="张磊" p:age="18">
    </bean>

    <!-- c命名注入,通过构造器注入-->
    <bean id="user2" class="cn.imut.pojo.User" c:age="18" c:name="张磊">
        
    </bean>

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

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

6.4 bean的作用域

  1. 单例模式(默认)

    <bean id="user2" class="cn.imut.pojo.User" c:age="18" c:name="张磊" scope="singleton">
  2. 原型模式

    <bean id="user2" class="cn.imut.pojo.User" c:age="18" c:name="张磊" scope="prototype">

    每次从容器get时,都会产生一个新的对象

  3. 其余的request、session、application只能在Web开发中使用到!

七、Bean的自动装配

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

在Spring中有三种自动装配方式

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

7.1 测试

环境搭建:一个人两个宠物

7.2 ByName自动装配

    <!--
        ByName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
    -->
    <bean id="people" class="cn.imut.pojo.People" autowire="byName">
        <property name="name" value="张磊"/>
    </bean>

7.3 ByType自动装配

byType:会自动在容器上下文中查找,和自己对象属性相同的对应的beanid
    <bean id="people" class="cn.imut.pojo.People" autowire="byType">
        <property name="name" value="张磊"/>
    </bean>

小结:

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

7.4 注解实现自动装配

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

要使用注解须知:

  1. 导入约束:context

        <context:annotation-config/>
  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:

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

可以不用写set方法,前提是在IOC容器中存在,且符合ByType

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解完成时

@Nullable: 字段标记此注解,字段可以为null

使用@Qualifier配合使用

@Qualifier(value = "dog1")      

@Resource

java自带注解,没有Spring方便

小结

@Resource和@Autowired的区别:

  • 都是用来自动装配,都可以放在属性字段上
  • @Autowired 通过ByType的方式实现,必须要求对象存在,否则空指针
  • @Resource默认通过ByName实现,若找不到名字,则通过ByType找
  • 执行顺序不同:@Autowired 通过byType的方式实现。@Resource默认通过byname的方式实现

八、使用注解开发

在Spring4之后,要使用注解开发,必须要保证aop的包导入了

使用注解需要导入context约束,增加注解的支持

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        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>
  1. bean

  2. 属性如何注入

    @Data
    @Component
    // @Component 组件
    public class User {
    
        //相当于bean中的注入
        @Value("张磊")
        public String name;
    }
  3. 衍生的注解

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

    • dao @Repository
    • service @Service
    • controller @Controller

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

  4. 自动装配

    @Autowired:自动装配,通过类型
    @Qualifier:配合使用,可以具体指定
    @Nullable: 字段标记此注解,字段可以为null
    @Resource:自动装配
  5. 作用域

    @Data
    @Component
    // @Component 组件
    @Scope("singleton") //单例
    public class User {
    
        //相当于bean中的注入
        @Value("张磊")
        public String name;
    }
  6. 小结

    xml与注解:
    • xml更加万能,适用于任何场合!维护简单方便
    • 注解 不是自己的类使用不了,维护相对复杂
    最佳实践:
    • xml用来管理bean
    • 注解只负责完成属性的注入

九、使用Java的方式配置Spring

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

@Configuration
public class MyConfig {

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

纯Java配置,在SpringBoot中随处可见

十、代理模式

代理模式是SpringAOP的底层!

代理模式的分类

  • 静态分类
  • 动态代理

10.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() {
        }
    
        public Proxy(Host host) {
            this.host = host;
        }
    
        public void rent() {
            seeHouse();
            host.rent();
            hetong();
            fare();
        }
    
        //看房
        public void seeHouse() {
            System.out.println("中介带你去看房");
        }
    
        //收中介费
        public void fare() {
            System.out.println("收中计费");
        }
    
        //签合同
        public void hetong() {
            System.out.println("签合同");
        }
    }
  4. 客户端访问代理角色

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

代理模式的好处:

  • 可以使真实角色更加纯粹!不用关心一些公共业务
  • 公告业务交给代理角色!实现了业务分工
  • 公告业务扩展时,方便集中管理

缺点:

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

10.2 加深理解

10.3 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的类是动态生成的,不是直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口--JDK动态代理【使用】
    • 基于类:cglib
    • Java字节码:javasist

需要了解两个类:Proxy:代理,InvocationHandler:调用处理程序

十一、AOP

AOP(Aspect Oriented Programming) 意为:面向切面编程

是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

AOP是OOP的一种延续,是软件开发的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。

利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各个部分之间的耦合度降低,提高程序的可重用性,同时提高开发效率。

AOP的作用及优势

  • 作用
    • 程序运行期间,不修改源码对已有方法进行增强
  • 优势
    • 减少重复代码
    • 提高开发效率
    • 维护方便

AOP在Spring中的作用

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

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

image-20200216110146242

使用String实现AOP

需要导入依赖包

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

方式一:使用Spring的接口

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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="cn.imut.service.UserServiceImpl"/>

    <bean id="log" class="cn.imut.log.Log"/>
    <bean id="afterLog" class="cn.imut.log.AfterLog"/>
    <!-- 方式一、使用原生Spring API 接口-->
    <!-- 配置aop 需要导入aop的配置-->
    <aop:config>
        <!-- 切入点:expression:表达式   execution(要执行的位置)-->
        <aop:pointcut id="pointcut" expression="execution(* cn.imut.service.UserServiceImpl.*(..))"/>
        <!-- 执行环绕增强-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //动态代理代理的是接口!
        UserService userService = (UserService) context.getBean("userService");

        userService.add();
    }
}

方式二:使用自定义类(主要是切面定义)

<!-- 方式二、自定义类-->
    <bean id="diy" class="cn.imut.diy.DiyPointCut"/>

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

测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //动态代理代理的是接口!
        UserService userService = (UserService) context.getBean("userService");

        userService.add();
    }
}

方式三:使用注解实现

    <!-- 方式三注册-->
    <bean id="annotationPointCut" class="cn.imut.diy.AnnotationPoint"/>

    <!-- 开启注解支持-->
    <aop:aspectj-autoproxy/>
@Aspect //标注这个类是一个切面
public class AnnotationPoint {

    @Before("execution(* cn.imut.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("该方法执行前");
    }
}

eg2

//用户记录日志的公共类
@Component("logger")
@Aspect //当前类是一个切面类
public class Logger {
    //用于打印日志,计划让其在切入点方法执行之前执行

    @Pointcut("execution(* cn.imut.service.Impl.*.*(..))")
    public void pt1() {
        System.out.println("哈哈");
    }
    @Before("pt1()")
    public void printLog() {
        System.out.println("Logger类中的printLog方法开始记录日志了");
    }
}

十二、整合Mybatis

步骤:

  1. 导入jar包
    • junit
    • mybatis
    • mysql
    • spring相关
    • aop植入
    • mybatis-spring [new]
  2. 编写配置文件
  3. 测试

12.1 回忆Mybatis

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

12.2 Mybatis-Spring

环境:

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.3</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>

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

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>
  1. 编写数据源配置

        <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&amp;serverTimezone=UTC"/>
            <property name="username" value="root"/>
            <property name="password" value="1870535196"/>
        </bean>
  2. sqlSessionFactory

        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- 绑定Mybatis 配置文件
                可以替代Mybatis配置文件
            -->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:cn/imut/mapper/UserMapper.xml"/>
        </bean>
  3. sqlSessionTemplate

        <!-- SqlSessionTemplate:就是我们使用的sqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <!-- 只能通过构造器注入,因为没有set方法-->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
  4. 接口加实现类

    public interface UserMapper {
        public List<User> selectUser();
    }
    public class UserMapperImpl implements UserMapper{
    
        //我们的所有操作都使用SqlSession来执行
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
        <bean id="userMapper" class="cn.imut.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
  5. 实现类注入Spring,测试

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

方式二

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    public List<User> selectUser() {
        SqlSession session = getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}
    <bean id="userMapper2" class="cn.imut.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

十三、声明式事务

回顾事务

  • 把一组事务当成一个业务来做要么都成功,要么都失败
  • 涉及到数据一致性的问题,不能马虎
  • 确保完整性和一致性

事务的ACID原则

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

Spring中的事务管理

  • 声明式事务:AOP
  • 编程事务:需要在代码中

image-20200216153742267

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

    <!-- 结合AOP实现事务的植入-->
    <!-- 配置事务的类-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务的传播特性      propagation 传播-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="update"/>
            <tx:method name="delete"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* cn.imut.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

猜你喜欢

转载自www.cnblogs.com/yfyyy/p/12335066.html