0


Spring笔记

Spring笔记

一、Spring概述

1.1、Spring框架是什么

​ Spring框架是可以在JavaSE/EE中使用的轻量级开源框架,目的是为了解决企业应用开发的复杂性而创建的,Spring的核心是控制反转(IoC)和面向切面编程(AOP)。

​ Spring的主要作用就是为代码 “解耦”,降低代码间的耦合度,就是让对象和对象(模块和模块)之间的关系不是使用代码关联,而是通过配置来说明。Spring根据代码的功能特点,使用IoC降低业务对象之间的耦合度。IoC使得主业务在相互调用过程中,不用再自己维护关系了,即不用再自己创建要使用的对象了。而是由Spring容器统一管理,自动“注入”,即赋值。而AOP使得系统级服务得到了最大复用,且不用再由程序员手工将系统级服务“混杂‘到主业务逻辑中了,而是由Spring容器统一完成"织入"。

1.2、Spring体系结构

在这里插入图片描述

​ Spring框架至今已集成了20多个模块,这些模块分布在核心容器(Core Container)、数据访问/集成(Data Access/Integration)层、Web层、AOP(Aspect Oriented Programming,面向切面的编程)模块、植入(Instrumentation)模块、消息传输(Messaging)和测试(Test)模块中。

二、Spring IoC

2.1、Spring IoC的基本概念

​ 控制反转(Inversion of Control,IoC)是一个比较抽象的概念,是一种思想,是Spring框架的核心,目的是减少对代码的改动,实现解耦合。指将传统上由程序代码直接操控的对象调用权交给容器,通过容器来实现对对象的装配和管理。控制反转就是对对象控制权的转移,从程序代码本身反转到了外部容器。通过容器实现对象的创建,属性赋值,依赖的管理。其实现方式很多,当前应用较为广泛的实现方式是依赖注入

​ 控制:创建对象,给对象的属性赋值,对象之间的关系管理。

​ 反转:把原来的开发人员管理,创建对象的权限转移给代码之外的容器实现。由容器代替开发人员管理对象,创建对象。

​ 正转:由开发人员在代码中,使用new构造方法创建对象,开发人员主动管理对象。

​ 依赖:类A中含有类B的实例,在类A中调用类B的方法完成功能,即类A对类B有依赖。

​ 依赖注入:(Dependency In jection,DI),只需要在程序中提供要使用的对象名称就可以,至于对象如何在容器中创建,赋值,查找都由容器内部实现。Spring是使用的DI实现了IoC的功能,Spring底层创建对象,使用的是反射机制。

​ Java中创建对象的方式:1、构造方法,new对象;2、反射;3、序列化;4、克隆;5、IoC,容器创建对象;6、动态代理。

​ IoC的体现:之前学习过的JavaWeb中的Servlet。1、创建类继承HttpServlet;2、在web.xml注册Servlet,使用<servlet-name>,<servlet-class>标签;3、没有创建Servlet对象,没有new XxxServlet();4、Servlet是Tomcat服务器为你创建的,Tomcat也称为容器。Tomcat作为容器,里面存放着Servlet对象,Listener、Filter对象。

2.2、Spring的第一个程序

使用maven工具来完成。

定义接口和实体类:

publicinterfaceSomeService{voiddoSome();}//实体类:publicclassSomeServiceImplimplementsSomeService{publicSomeServiceImpl(){System.out.println("SomeServiceImpl类的无参构造方法执行了!");}@OverridepublicvoiddoSome(){System.out.println("执行了SomeServiceImpl的doSome方法");}}

创建spring配置文件:

​ 在src/main/resource/目录下创建一个xml文件,文件名可以随意,推荐使用application Context。spring配置中需要加入约束文件才能正常使用,约束文件是xsd扩展名。

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd"><!--告诉Spring创建对象
        声明bean:就是告诉spring要创建某个类的对象
        id:对象的自定义名称,唯一值,spring通过这个名称找到对象,bean与Bean之间的依赖关系也是通过id属性关联
        class:类的全限定名称(不能是接口,因为spring是通过反射机制创建对象,必须使用类)

        spring就完成 SomeServiceImpl service = new SomeServiceImpl();
        spring是把创建好的对象放到map中,spring框架内部有一个map存放对象的
        springMap.put(id的值,对象);
        一个bean标签声明一个对象
     --><beanid="someService"class="com.service.impl.SomeServiceImpl"/><beanid="someService1"class="com.service.impl.SomeServiceImpl"/><!--
        spring可以创建一个非自定义类的对象,创建一个存在的某个类的对象。
    --><beanid="myDate"class="java.util.Date"/></beans><!--
   spring的配置文件
   1、beans:是根标签,spring把java对象称为bean
   2、spring-beans.xsd 是约束文件,和mybatis指定 dtd是一样的
-->

定义测试类:

/**
     *  spring默认创建对象的时间 : 在创建spring容器时,会创建配置文件中的所有的对象
     *  spring创建对象,默认调用的是无参数的构造方法
     */@Testpublicvoidtest02(){//使用spring容器创建对象//1、指定spring配置文件的名称String config ="beans.xml";//2、创建表示spring容器的对象,ApplicationContext//ApplicationContext就是表示Spring容器,通过容器获取对象了//ClassPathXmlApplicationContext:表示从类路径中加载spring的配置文件ApplicationContext ac =newClassPathXmlApplicationContext(config);//从容器中获取某个对象,要调用对象的方法SomeService service =(SomeService) ac.getBean("someService");//使用spring创建好的对象
        service.doSome();}

Spring还可以创建非自定义类对象。

容器接口和实现类:

ApplicationContext接口(容器)

​ ApplicationContext用于加载Spring的配置文件,在程序中充当 ”容器“ 的角色。其实现类有两个。

在这里插入图片描述

​ 若Spring配置文件存放在项目的类路径下,则使用ClassPathXmlApplicationContext实现类进行加载。

​ ApplicationContext容器,会在容器对象初始化时,将其中的所有对象一次性全部装配好。以后代码中若要是用到这些对象,只需从内存中直接获取即可。(执行效率高,但占用内存。)

使用Spring容器创建的java对象:

在这里插入图片描述

2.3、基于XML的DI

2.3.1、注入的分类

bean实例在调用无参构造器创建对象后,就要对bean对象的属性进行初始化。初始化是由容器自动完成的,称为注入。根据注入的方式不同,常用的有两类:set注入、构造注入。

(1)使用setter方法注入

使用setter方法注入是spring框架中最主流的注入方式,他利用Java Bean规范的所定义的setter方法来完成注入,灵活且可读性高。对于setter方法注入,Spring框架也是使用Java的反射方式实现的。

简单类型:spring中规定java的基本数据类型和String都是简单类型

Student类:

publicclassStudent{privateString name;privateInteger age;//setter//toString()}

Spring配置文件,applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--声明student对象
        注入:就是赋值的意思
        简单类型:spring中规定java的基本数据类型和String都是简单类型
        di:给属性赋值
        1、set注入(设置注入):spring调用类的set方法,可以在set方法中完成属性的赋值
          1)简单类型的set注入
            <bean id="xx" class="yyy">
                <property name="属性名" value="此属性的值" />
                一个property只能给一个属性赋值
                <property..../>
            </bean>
    --><beanid="myStudent"class="com.ba01.Student"><propertyname="name"value="张三"/><!--setName("张三")--><propertyname="age"value="18"/><!--setName(18)--></bean></beans>

测试类:

@Testpublicvoidtest01(){String config ="ba01/applicationContext.xml";ApplicationContext ac =newClassPathXmlApplicationContext(config);//从容器中获取对象Student myStudent =(Student) ac.getBean("myStudent");System.out.println("student对象="+ myStudent);}

引用类型:当指定bean的某属性值为另一bean的实例时,通过ref指定它们间的关系。ref的值必须为某bean的id值。

Student类:

packagecom.ba02;publicclassStudent{privateString name;privateInteger age;privateSchool school;//settter//toString()}

School类:

packagecom.ba02;publicclassSchool{privateString name;privateString address;//setter//toString()}

Spring配置文件,applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--    2)引用类型的set注入
        <bean id="xx" class="yyy">
            <property name="属性名" ref="bean的id(对象的名称)" />
        </bean>
--><beanid="myStudent"class="com.ba02.Student"><propertyname="name"value="张三"/><!--setName("张三")--><propertyname="age"value="18"/><!--setName(18)--><!--引用类型--><propertyname="school"ref="mySchool"/><!--setSchool(mySchool)--></bean><!--声明School对象--><beanid="mySchool"class="com.ba02.School"><propertyname="name"value="xpu"/><propertyname="address"value="西安"/></bean></beans>

对于其他Bean对象的引用,使用<bean/>标签的ref属性

测试类:

@Testpublicvoidtest01(){String config ="ba02/applicationContext.xml";ApplicationContext ac =newClassPathXmlApplicationContext(config);Student myStudent =(Student) ac.getBean("myStudent");System.out.println("myStudent: "+ myStudent);}
(2)构造注入

构造注入是指,在构造调用者实例的同时,完成被调用者的实例化。即,使用构造器设置依赖关系。

//有参数构造方法    publicStudent(String name,Integer age,School school){System.out.println("Student的有参数构造方法执行了!");this.name = name;this.age = age;this.school = school;}
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--
    2、构造注入:spring调用类的有参数构造方法,在创建对象的同时,在构造方法中给属性赋值
    构造注入使用<constructor-arg>标签
    <constructor-arg>标签:一个<constructor-arg>表示构造方法一个参数。
    <constructor-arg>标签属性:
        name:表示构造方法的形参名
        index:表示构造方法的参数位置,参数从左往右位置是0,1,2的顺序
        value:构造方法的形参类型是简单类型的使用value
        ref:构造方法的形参类型是引用类型的使用ref
--><!--使用name属性完成构造注入--><beanid="myStudent"class="com.ba03.Student"><constructor-argname="name"value="Danny"/><constructor-argname="age"value="15"/><constructor-argname="school"ref="mySchool"/></bean><!--使用index属性完成构造注入--><beanid="myStudent2"class="com.ba03.Student"><constructor-argindex="0"value="Jenny"/><constructor-argindex="1"value="25"/><constructor-argindex="2"ref="mySchool"/></bean><!--声明School对象--><beanid="mySchool"class="com.ba03.School"><propertyname="name"value="haFo"/><propertyname="address"value="America"/></bean><!--使用构造注入创建一个系统类File对象--><beanid="myFile"class="java.io.File"><constructor-argname="parent"value="E:\QQ文件"/><constructor-argname="child"value="蓝桥杯校赛.doc"/></bean></beans>

<constructor-arg />标签中用于指定参数的属性有:

name:指定参数名称

index:指明该参数对于着构造器的第几个参数,从0开始,不过,该属性不要也行,但要注意,若参数类型相同,则需要保证赋值顺序要与构造器中的参数顺序一致。

publicclassMyTest03{@Testpublicvoidtest01(){String config ="ba03/applicationContext.xml";ApplicationContext ac =newClassPathXmlApplicationContext(config);Student myStudent =(Student) ac.getBean("myStudent");System.out.println(myStudent);}@Testpublicvoidtest02(){String config ="ba03/applicationContext.xml";ApplicationContext ac =newClassPathXmlApplicationContext(config);Student myStudent =(Student) ac.getBean("myStudent2");System.out.println(myStudent);}@Testpublicvoidtest03(){String config ="ba03/applicationContext.xml";ApplicationContext ac =newClassPathXmlApplicationContext(config);File myFile =(File) ac.getBean("myFile");System.out.println(myFile.getName());}}

2.3.2、引用类型属性自动注入

​ 对于引用类型属性的注入,也可不在配置文件中显式的注入。可以通过为<bean/>标签设置autowire属性值,为引用类型属性进行隐式自动注入(默认是不自动注入引用类型属性)。根据自动注入判断标准的不同,可以分为两种:byName:(根据名称自动注入)、byType:根据类型自动注入

(1)byName方式自动注入

​ Java类中引用类型的属性名和spring容器中(配置文件)<bean>的id名称一样。且数据类型是一致的,这样的容器中的bean,spring能够赋值给引用类型。

publicclassStudent{privateString name;privateInteger age;privateSchool school;//setter//toString}
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--byName--><beanid="myStudent"class="com.ba04.Student"autowire="byName"><propertyname="name"value="张三"/><!--setName("张三")--><propertyname="age"value="18"/><!--setName(18)--></bean><!--声明School对象--><beanid="school"class="com.ba04.School"><propertyname="name"value="xu"/><propertyname="address"value="xian"/></bean></beans>
(2)byType方式自动注入

byType(按类型注入):Java类中引用类型的数据类型和spring容器中(配置文件)<bean>的class属性同源关系的,这样的bean能够赋值给引用类型。

​ 1、Java类中引用类型的数据类型和bean的class的值是一样的
​ 2、Java类中引用类型的数据类型和bean的class的值是父子关系的
​ 3、Java类中引用类型的数据类型和bean的class的值是接口和实现类关系的

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--byType--><beanid="myStudent"class="com.ba05.Student"autowire="byType"><propertyname="name"value="王五"/><!--setName("张三")--><propertyname="age"value="19"/><!--setName(18)--></bean><!--声明School对象--><beanid="mySchool"class="com.ba05.School"><propertyname="name"value="lj"/><propertyname="address"value="xian"/></bean></beans>

使用byType自动注入首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

2.3.3、为应用指定多个Spring配置文件

​ 在实际应用中,随着应用规模的增加,系统bean数量也大量增加,导致配置文件变得非常庞大。为了避免这种情况的发生,提高配置文件的可读性与可维护性,可以将Spring配置文件分解成多个配置文件。

包含关系的配置文件:

​ 多个配置文件中有一个总文件,总配置文件将各其他子文件通过<import/>引入。在java代码中只需使用总配置文件对容器进行初始化即可。

spring-student.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><beanid="myStudent"class="com.ba06.Student"autowire="byType"><propertyname="name"value="王五"/><!--setName("张三")--><propertyname="age"value="19"/><!--setName(18)--></bean></beans>

​ spring-school.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--声明School对象--><beanid="mySchool"class="com.ba06.School"><propertyname="name"value="lj"/><propertyname="address"value="xian"/></bean></beans>

total.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--
        total表示主配置文件:包含其他的配置文件的。注配置文件一般是不定义对象的
        语法:<import resource="其他配置文件的路径"/>
        关键字:“classpath”表示类路径(class文件所在的目录)
                在spring的配置文件中要制定其他文件的位置,需要使用classpath,告诉spring到哪去加载读取文件
    --><importresource="classpath:06包含关系的配置文件/spring-school.xml"/><importresource="classpath:06包含关系的配置文件/spring-student.xml"/><!--两者选其一--><!--
        在包含关系的配置文件中,可以使用通配符(*:表示任意字符)
        注意:主的配置文件名称不能包含在通配符范围内(不能叫做spring-total.xml)
        如果要用通配符这种方案指定多个文件,spring规定:这些文件必须放在同一级目录之中
    --><!--<import resource="classpath:06包含关系的配置文件/spring-*.xml" />--></beans>

也可使用通配符。但此时要求父配置文件名不能满足所能匹配的格式,否则将出现循环递归包含。

注意:如果要用通配符这种方案指定多个文件,spring规定:这些文件必须放在同一级目录之中。

2.4、基于注解的DI

对于DI使用注解,将不需要在Spring配置文件中声明bean实例。Spring中使用注解,需要在Spring配置文件中配置组件扫描器,用于指定的基本包中扫描注解。

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--声明组件扫描器(component-scan),组件就是java对象
        base-package:指定注解在你的项目中的包名
        component-scan的工作方式:spring会扫描遍历base-package指定的包1
            把包中和子包中的所有类,找到类中的注解,按照注解的功能创建对象或给属性赋值
    --><context:component-scanbase-package="com.anno.Component"/></beans>

指定多个包的三种方式:

第一种方式:使用多个组件扫描器,指定不同的包

第二种方式:使用分隔符(;或,)分隔多个包名

第三种方式:指定父包,但不建议使用顶级的父包,扫描的路径比较多,导致容器启动时间变慢。

2.4.1定义Bean的注解@Component

需要在类上使用注解@Component,该注解的value属性用于指定该bean的id值。

//使用value属性,指定对象名称//@Component(value = "myStudent")//省略value  (这个用的最多)@Component("myStudent")//不指定对象名称,由spring提供默认名称:类名的首字母小写//@ComponentpublicclassStudent{String name;Integer age;}

spring中和@Component功能一致,创建对象的注解还有:

1、@Repository(用在持久层类的上面):放在dao的实体类上面。表示创建dao对象,dao对象是能访问数据库的。

2、@Service(用在业务层类的上面):放在service的实体类上面。创建service对象。service对象是做业务处理,可以有事务等功能的

3、@Controller(用在控制器的上面):放在控制器(处理器)类的上面,创建控制器对象的。控制器对象:能够接收用户提交的参数,显示请求的处理结果

以上三个注解的使用语法和@Component一样的,都能创建对象,但是这三个注解还有额外的功能。

@Repository、@Service、@Controller是给项目的对象分层的。

2.4.2 简单类型属性注入@Value

需要在属性上使用注解@Value,该注解的value属性用于指定要注入的值。

使用该注解完成属性注入时,类中无需setter。若属性有setter,则也可以将其加到setter上。

@Component("student")publicclassStudent{@Value("李四")String name;@Value("18")Integer age;}

2.4.3 byType自动注入@Autowired

需要在引用属性上使用注解@Autowired,该注解默认使用按类型自动装配bean的方式。

使用该注解完成属性注入时,类中无需setter。若属性有setter,则也可以将其加到setter上。

@Component("student1")publicclassStudent{@Value("李四")privateString name;@Value("18")privateInteger age;/**
     * 引用类型
     * @Autowired:spring框架提供的注解,实现引用数据类型赋值
     * spring中通过注解给引用数据类型赋值的,使用的是自动注入原理,支持byType、byName
     * @Autowired默认使用的是byType自动注入
     *  属性:required:是一个boolean类型的,默认为true
     *       required=true。表示引用类型如果赋值失败,程序报错,并终止执行
     *       required=false,表示引用类型如果赋值失败,程序正常执行,引用类型是null
     *  位置:1、在属性定义的上面,无需set方法,推荐使用
     *       2、在set方法上面
     *  如果要用byName方式,需要做的是:
     *      1、在属性上面加入@Autowired
     *      2、在属性上面加入@Qualifier(value="bean的id")
     */@Autowired@Qualifier("school")privateSchool school;}

使用byType自动注入首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

2.4.4 byName自动注入@Autowired与@Qualifier

需要在引用属性上联合使用注解@Autowired与@Qualifier。@Qualifier的value属性用于指定要匹配的bean的id值。

@Autowired还有一个属性required,是一个boolean类型的,默认为true

required=true。表示引用类型如果赋值失败,程序报错,并终止执行。 required=false,表示引用类型如果赋值失败,程序正常执行,引用类型是null。

2.4.5 JDK注解@Resource自动注入

Spring提供了对jdk中@Resource注解的支持。@Resource注解可以按名称匹配bean。也可以按类型匹配bean。默认是按名称注入

(1)byType注入引用类型属性

@Resource注解若不带任何参数,采用默认按名称的方式注入,按名称不能注入bean,则会按照类型进行bean的匹配注入。

(2)byName注入引用类型属性

@Resource注解指定其name属性,则name的值即为按照名称进行匹配的bean的id。

@Component("student2")publicclassStudent{@Value("李四")privateString name;@Value("18")privateInteger age;/**
     * 引用类型
     * @Resource 来自jdk中的注解,spring框架提供了对这个注解的功能支持,可以使用
     *            他给引用类型赋值。使用是也是自动注入原理,支持byName、byType,默认byName
     *  位置:1、在属性定义的上面,无需set方法,推荐使用
     *       2、在set方法的上面
     *  默认是byName:先使用byName自动注入,如果byName赋值失败,再使用byType
     * @Resource只使用byName的方式,需要增加一个属性:name
     * name的值是bean的id
     */@Resource(name ="school1")privateSchool school;

2.5、注解与XML的对比

注解的优点是:方便、直观、高效(代码少,没有配置文件的书写那么复杂)。

注解的缺点是:以硬编码的方式写入到Java代码中,修改是需要重新编译代码的。

XML的优点是:配置文件和代码是分离的;在xml中做修改,无需编译代码,只需重启服务器即可将新的配置加载。

XML的缺点是:编写麻烦,效率低,大型项目过于复杂。

2.6、IoC能实现解耦合

IoC能实现业务对象之间的解耦合,例如service和dao对象之间的解耦合。

三、AOP面向切面编程

3.1、回顾动态代理

实现方式:

jdk动态代理,使用jdk中的Proxy、Method、InvocaitonHanderl创建代理对象。jdk动态代理要求目标类必须实现接口。

cglib动态代理:第三方的工具库,创建代理对象,原理是继承。通过继承目标类,创建子类。子类就是代理对象。要求目标类不能是final修饰的,方法也不能是final的。

动态代理的作用:

1、在目标类源代码不改变的情况下,增加功能。

2、减少代码的重复

3、专注业务逻辑代码

4、解耦合,让你的业务功能和日志,事务等非业务功能分离。

3.2、AOP面向切面编程

AOP(Aspect Orient Programming):面向切面编程,基于动态代理的,可以使用jdk、cglib两种代理方式。AOP就是动态代理的规范化,把动态代理的实现步骤,方法都定义好了,让开发人员使用统一的方式使用动态代理。

Aspect:切面,给你的目标类增加的功能,就是切面。像日志、事务都是切面。切面的特点:一般都是非业务方法,独立使用的

Orient:面向、对着。

如何理解面向切面编程:

1、需要在分析项目功能时,找出切面。

2、合理的安排切面的执行时间(在目标方法前,还是目标方法后)

3、合理的安排切面执行的位置,在哪个类,哪个方法增强功能。

使用AOP的好处是可以减少重复代码,专注业务实现。

3.3、AOP的术语

(1)切面(Aspect)

表示增强的功能,就是一堆代码完成某个功能。非业务功能。常见的切面功能有日志,事务,统计信息,参数检查,权限验证等。

(2)连接点(JoinPoint)

连接业务方法和切面的位置。就某类中的业务方法。

(3)切入点(Pointcut)

指多个连接点方法的集合。多个方法

(4)目标对象(Target)

给哪个类的方法增强功能,这个类就是目标对象。

(5)通知(Advice)

表示切面的执行时间,Advice也叫增强。换个角度说,通知定义了增强代码切入到目标代码的时间点,是目标方法执行之前执行,还是之后执行。

切入点定义切入的位置,通知定义切入的时间。

3.4、AOP的实现

AOP是一个规范,是动态的一个规范化,一个标准。

AOP的技术实现框架:

1、Spring:Spring在内部实现了aop规范,能做aop的工作。spring主要在事务处理时使用AOP。我们在项目开发中很少使用spring的aop实现,因为spring的aop比较笨重。

2、AspectJ:一个开源的专门做AOP的框架。spring框架中集成了aspectj框架,通过spring就能使用aspectj的功能。

AspectJ框架实现AOP有两种方式:

1、使用xml的配置文件:配置全局事务

2、使用注解,我们在项目中要做AOP的功能,一般都使用注解,AspectJ有5个注解

3.5、AspectJ框架的使用

3.5.1、AspectJ中常用的通知有五种类型:

1)前置通知 @Before

2)后置通知 @AfterReturning

3)环绕通知 @Around

4)异常通知 @AfterThrowing

5)最终通知 @After

3.5.2、AspectJ的切入点表达式

Aspectj定义了专门的表达式用于指定切入点,表达式原型:

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern) throws-pattern?)

?表示可选部分

以上表达式共4个部分:

execution(访问权限 方法返回值 方法声明(参数) 异常类型)

切入点表达式要匹配的对象就是目标方法的方法名。所以execution表达式中明显就是方法的签名。注意,表达式中未加粗文字表示可省略部分,各部分之间用空格隔开。在其中可以使用以下符号:

  • 意义:0至多个任意字符

… 意义:用在方法参数中,表示任意多个参数。用在包名后,表示当前包及其子包路径。

例如:

execution(* set*(…)) 指定切入点为:任何一个以“set”开始的方法。

execution(* com.xyz.service..(…)) 指定切入点为:定义在 service 包里的任意类的任意方法。

execution(* com.xyz.service…*.(…)) 指定切入点为:定义在 service 包或者子包里的任意类的任意方法。**“…”出现在类名中时,后面必须跟“”,表示包、子包下的所有类。**

execution(* …service..*(…)) 指定所有包下的 serivce 子包下所有类(接口)中所有方法为切入点.

3.5.3、AspectJ基于注解的AOP实现

配置文件applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--把对象交给spring容器,由spring容器统一创建、管理对象--><!--声明自动代理生成器:使用aspectj框架内部的功能,创建目标对象的代理对象,
        创建代理对象是在内存中实现的,修改目标对象的内存中的功能,创建为代理对象
        所以目标对象就是被修改后的代理对象
        aspectj-autoproxy:会把spring容器中的所有的目标对象,一次性都生成代理对象
    --><context:component-scanbase-package="com.ba01"/><aop:aspectj-autoproxy/></beans>

接口和实现类:

//接口publicinterfaceSomeService{voiddoSome(String name,Integer age);}//目标类@Component("someService")publicclassSomeServiceImplimplementsSomeService{@OverridepublicvoiddoSome(String name,Integer age){//给doSome这个方法增加一个功能,在doSome()执行之前,输出方法的执行时间System.out.println("目标方法doSome");}}
(1)@Before前置通知

切面类:

/**
 * @Aspect: 是aspectj框架中的注解
 *       作用:表示当前类是切面类
 *       切面类: 是用来给业务方法增加功能的类,在这个类中有切面的功能代码
 *       位置:在类定义的上面
 */@Aspect@Component("myAspect")publicclassMyAspect{/**
     * 定义方法,方法是实现切面功能的
     * 方法定义要求:
     *  1、公共方法 public
     *  2、方法没用返回值
     *  3、方法名称自定义
     *  4、方法可以有参数,也可以没参数
     *      如果有参数,参数不是自定义的,有几个参数类型可以使用
     *//**
     * @Before:前置通知注解
     *  属性:value,是切入点表达式,表示切面的功能执行的位置
     *  位置:在方法的上面
     * 特点:
     *  1、在目标方法之前先执行的
     *  2、不会改变目标方法的执行结果
     *  3、不会影响目标方法的执行
     */@Before(value ="execution(* *..SomeServiceImpl.doSome(String,Integer))")publicvoidmyBefore(){//就是切面要执行的代码System.out.println("3==前置通知,切面功能:在目标方法之前输出执行时间: "+newDate());}/**
     * 指定通知方法中的参数:JoinPoint
     * JoinPoint:业务方法,要加入切面功能的业务方法
     *      作用是:可以在通知方法中获取方法执行时的信息,例如方法名称,方法实参。
     *      如果你的切面功能中需要用到方法的信息,就加入JoinPoint
     *      这个JoinPoint参数的值是由框架赋予,必须是第一个位置的参数
     */@Before(value ="execution(void *..SomeServiceImpl.doSome(String,Integer))")publicvoidmyBefore(JoinPoint jp){//获取方法的完整定义System.out.println("方法的签名(定义)= "+jp.getSignature());System.out.println("方法的名称= "+jp.getSignature().getName());//获取方法的实参Object[] args = jp.getArgs();for(Object arg : args){System.out.println("参数:"+ arg);}//就是切面要执行的代码System.out.println("2==前置通知,切面功能:在目标方法之前输出执行时间: "+newDate());}}
(2)@AfterReturning后置通知

目标类的目标方法:

@OverridepublicStringdoOther(String name,Integer age){System.out.println("目标方法doOther()!");return"abcd";}

切面类:

@Aspect@Component("myAspect")publicclassMyAspect{/**
     * 后置通知定义方法,方法是实现切面功能的
     * 方法定义要求:
     *  1、公共方法 public
     *  2、方法没用返回值
     *  3、方法名称自定义
     *  4、方法有参数,推荐使用Object,参数名自定义
     *//**
     * @AfterReturning:后置通知
     *    属性:1、value 切入点表达式
     *    2、returning 自定义变量,表示目标方法的返回值的
     *      自定义变量名必须和通知方法的形参名一样
     *    使用位置:方法定义的上面
     * 特点:
     *    1、在目标方法之后执行的
     *    2、能够获取到目标方法的返回值,可以根据这个返回值做不同的处理功能
     *    3、可以修改这个返回值
     *
     *    后置通知的执行:
     *    Object res = doOther();
     *    myAfterReturning(res);
     */@AfterReturning(value ="execution(* *..SomeServiceImpl.doOther(..))",returning ="res")publicvoidmyAfterReturning(Object res){//Object res: 是目标方法执行后的返回值,根据返回值做你的切面的功能处理System.out.println("后置通知:在目标方法之后执行的,获取的返回值是: "+res);}}
(3)@Around环绕通知

实现类的目标方法:

@OverridepublicStringdoFirst(String name,Integer age){System.out.println("业务方法doFirsst()!");returnnull;}

切面类

@Aspect@Component("myAspect")publicclassMyAspect{/**
     * 环绕通知方法的定义格式
     *  1、public
     *  2、必须有一个返回值,推荐使用Object
     *  3、方法名称自定义
     *  4、方法有参数,固定的参数:ProceedingJoinPoint
     *//**
     * @Around:环绕通知
     * 属性:value 切入点表达式
     * 特点:
     *  1、他是功能最强的通知
     *  2、可以在目标方法的前和后都能增加功能
     *  3、控制目标方法是否被调用执行
     *  4、修改原来的目标方法的执行结果,影响最后的调用结果
     *  等同于jdk动态代理的 invocationHandler接口
     *  参数:ProceedingJoinPoint等同于Method
     *      作用:执行目标方法的
     *  返回值:就是目标方法的执行结果,可以修改的
     *  环绕通知:经常做事务,在目标方法之前开启事务,执行目标方法,在方法执行之后提交事务
     */@Around(value ="execution(* *..SomeServiceImpl.doFirst(..))")publicObjectmyAround(ProceedingJoinPoint pjp)throwsThrowable{String name ="";//获取第一个参数值Object[] args = pjp.getArgs();if(args!=null&& args.length >1){Object arg = args[0];
            name =(String) arg;}//实现环绕通知Object result =null;System.out.println(newDate());//目标方法调用if("zhangsan".equals(name)){
            result = pjp.proceed();}System.out.println("提交事务");//在目标方法的前或者后增加功能//修改目标方法的执行结果,影响方法最后的调用结果if(result !=null){
            result ="Hello AspectJ AOP";}return result;}}
(4)@AfterThrowing异常通知

目标类及其目标方法:

@OverridepublicvoiddoSecond(){System.out.println("执行业务方法doSecond()!"+10/0);}

切面类:

@Aspect@Component("myAspect")publicclassMyAspect{/**
     * 异常通知方法的定义格式
     *  1、public
     *  2、没有返回值
     *  3、方法名称自定义
     *  4、方法有一个参数是Exception,如果还有是JoinPoint
     *//**
     * @AfterThrowing:异常通知
     *  属性:1、value:切入点表达式
     *       2、throwing自定义的变量,表示目标方法抛出的异常对象
     *          变量名必须和方法的参数名一样
     *  特点:
     *      1、在目标方法中抛出异常时才执行
     *      2、可以做异常的监控程序,监控目标方法执行时是不是有异常
     *          如果有异常,可以发生邮件、短信等通知
     *   执行流程:
     *      try{
     *          SomeServiceImpl.doSecond(..);
     *      } catch(Exception e) {
     *          myAfterThrowing(e);
     *      }
     */@AfterThrowing(value ="execution(* *..SomeServiceImpl.doSecond(..))",
                throwing ="ex")publicvoidmyAfterThrowing(Exception ex){System.out.println("异常通知,方法发生异常时,执行:"+ex);//发送邮件或者短信}}
(5)@After最终通知
@Aspect@Component("myAspect")publicclassMyAspect{/**
     * 最终通知方法的定义格式
     *  1、public
     *  2、没有返回值
     *  3、方法名称自定义
     *  4、方法没有参数,如果有就是JoinPoint
     *//**
     * @After:最终通知
     *  属性:value 切入点表达式
     *  位置:在方法上面
     * 特点:
     *  1、总是会执行
     *  2、在目标方法之后执行的
     *    执行流程:
     *      try{
     *          SomeServiceImpl.doThird(..);
     *      } catch(Exception e) {
     *      } finally {
     *          myAfter();
     *      }
     *
     */@After(value ="execution(* *..SomeServiceImpl.doThird(..))")publicvoidmyAfter(){System.out.println("执行最终通知,总是会被执行的代码");//一般做资源清除工作的}}
(6)@Pointcut定义切入点

当较多的通知增强方法使用相同的execution切入点表达式时,编写、维护较为麻烦。AspectJ提供了@Pointcut注解,用于定义execution切入点表达式

@After(value ="mypt()")publicvoidmyAfter(){System.out.println("执行最终通知,总是会被执行的代码");//一般做资源清除工作的}@Before(value ="mypt()")publicvoidmyBefore(){System.out.println("前置通知,在目标方法之前先执行的");//一般做资源清除工作的}/**
     * @Pointcut:定义和管理切入点: 如果你的项目中有多个切入点是重复的,可以复用的
     *            可以使用Pointcut
     *    属性:value 切入点表达式
     *    位置:在自定义方法的上面
     * 特点:
     *    当使用@Pointcut定义在一个方法的上面,此时这个方法的名称就是切入点表达式的别名
     *    其他的通知中value就可以使用这个方法的名称来代替切入点表达式
     */@Pointcut(value ="execution(* *..SomeServiceImpl.doThird(..))")privatevoidmypt(){//无需代码}

补充:在spring配置文件中:

<aop:aspectj-autoproxy/><!--使用的是jdk动态代理--><!--
        如果你期望目标类有接口,使用cglib动态代理
        proxy-target-class="true":告诉框架,要使用cglib动态代理
    --><aop:aspectj-autoproxyproxy-target-class="true"/>

四、Spring集成Mybatis

将Mybatis和Spring进行整合,主要解决的问题就是将SqlSessionFactory对象交由Spring来管理。所以只需要将SqlSessionFactory的对象生成器SqlSessionFactoryBean注册在Spring容器中,再将其注入给Dao的实现类即可。

用的技术是ioc。能把mybatis和spring集成在一起,像一个框架,是因为ioc能创建对象。可以把mybatis框架中的对象交给spring统一创建,开发人员从spring中获取对象。

因此,我们需要让Spring创建以下对象:

1、独立的数据库连接池类对象,使用阿里的druid连接池

2、SqlSessionFactory对象

3、创建出dao对象.

数据库连接池:多个连接Connection对象的集合。

List<Connection> connlist : connList就是连接池。

步骤:

1、新建maven,加入maven依赖 :

​ 1)spring依赖, 2)mybatis依赖, 3)mysql驱动, 4)spring的事务的依赖 ,5)mybatis和spring集成的依赖:mybatis官方提供的,用来在spring中创建mybatis的SqlSessionFactory,dao对象的。

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.idea</groupId><artifactId>spring-mybatis</artifactId><version>1.0-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><!--单元测试的依赖--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><!--spring依赖--><!-- https://mvnrepository.com/artifact/org.springframework/spring-context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.5.RELEASE</version></dependency><!--做spring事务用到的--><!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.2.5.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.5.RELEASE</version></dependency><!--mybatis的依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.8</version></dependency><!--mybatis和spring集成的依赖--><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency><!--阿里公司的数据库连接池--><!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.12</version></dependency></dependencies><build><!--目的是把src/main/java目录中的xml文件包含到输出结果中,输出到classes目录中--><resources><resource><directory>src/main/java</directory><!--所在的目录--><includes><!--包括目录下的.xml,.properties文件都会扫描到--><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build></project>

2、创建实体类

packagecom.domain;publicclassStudent{//属性和列名一样privateInteger id;privateString name;privateString email;privateInteger age;publicStudent(){}publicStudent(Integer id,String name,String email,Integer age){this.id = id;this.name = name;this.email = email;this.age = age;}publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name = name;}publicStringgetEmail(){return email;}publicvoidsetEmail(String email){this.email = email;}publicIntegergetAge(){return age;}publicvoidsetAge(Integer age){this.age = age;}@OverridepublicStringtoString(){return"Student{"+"id="+ id +", name='"+ name +'\''+", email='"+ email +'\''+", age="+ age +'}';}}

3、创建dao接口和mapper文件

packagecom.dao;importcom.domain.Student;importjava.util.List;publicinterfaceStudentDao{intinsertStudent(Student student);List<Student>selectStudents();}

mapper文件:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.dao.StudentDao"><selectid="selectStudents"resultType="com.domain.Student">
        select id,name,email,age from student order by id desc
    </select><insertid="insertStudent">
        insert into student values(#{id},#{name},#{email},#{age})
    </insert></mapper>

4、创建mybatis主配置文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><settings><settingname="logImpl"value="STDOUT_LOGGING"/></settings><!--设置别名--><typeAliases><!--name:实体类所在的包名。这个包下所有类的类名就是别名--><packagename="com.domain"/></typeAliases><!--sql映射文件的位置--><mappers><!--name是包名,这个包中的所有mapper.xml一次都能加载--><packagename="com.dao"/></mappers></configuration>

5、创建service接口和实现类,属性是dao

//service接口:packagecom.service;importcom.domain.Student;importjava.util.List;publicinterfaceStudentService{intaddStudent(Student student);List<Student>queryStudents();}//service接口实现类publicclassStudentServiceImplimplementsStudentService{privateStudentDao studentDao;publicvoidsetStudentDao(StudentDao studentDao){this.studentDao = studentDao;}@OverridepublicintaddStudent(Student student){int nums = studentDao.insertStudent(student);return nums;}@OverridepublicList<Student>queryStudents(){List<Student> students = studentDao.selectStudents();return students;}}

6、创建spring的配置文件:声明mybatis的对象交给spring创建:

​ 1)数据源,2)SqlSessionFactory,3)Dao对象,4)声明自定义的service,

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--要把数据库的配置信息,写在一个独立的配置文件中,编译修改数据库的配置内容
        要让spring知道配置文件的位置
    --><context:property-placeholderlocation="classpath:jdbc.properties"/><!--声明数据源DataSource,作用是连接数据库的--><beanid="myDataSource"class="com.alibaba.druid.pool.DruidDataSource"init-method="init"destroy-method="close"><!--set注入给DruidDataSource提供连接数据库信息--><!--使用属性配置文件中的数据,语法: ${key}--><propertyname="url"value="${jdbc.url}"/><!--对应的是setUrl()--><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></bean><!--声明mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!--set注入,把数据库连接池赋给了dataSource属性--><propertyname="dataSource"ref="myDataSource"/><!--mybatis主配置文件的位置
            configLocation属性是Resource类型,读取配置文件的
            它的赋值,使用value,指定文件路径,使用classpath:表示文件的位置
        --><propertyname="configLocation"value="classpath:mybatis.xml"/></bean><!--创建dao对象,使用SqlSession的getMapper(StudentDao.class)
        MapperScannerConfigurer:在内部使用getMapper()生成每个dao接口的代理对象。
    --><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--指定SqlSessionFactory对象的id--><propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/><!--指定包名,包名是dao接口所在的类名
            MapperScannerConfigurer会扫描这个包中所有的接口,把每个接口都
            执行一次getMapper()方法,得到每个接口的dao对象
            创建好的dao对象放到spring容器中的,dao对象的默认名称是:接口名首字母小写
        --><propertyname="basePackage"value="com.dao"/></bean><!--声明service--><beanid="studentService"class="com.service.impl.StudentServiceImpl"><!--向service注入--><propertyname="studentDao"ref="studentDao"/></bean></beans>

属性配置文件jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/数据库名
jdbc.username=数据库名
jdbc.password=数据库密码

7、创建测试类,获取service对象,通过service调用dao完成数据库的访问

packagecom;importcom.dao.StudentDao;importcom.domain.Student;importcom.service.StudentService;importorg.junit.Test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importjava.util.List;publicclassMyTest01{@TestpublicvoidtestServiceInsert(){String config ="applicationContext.xml";ApplicationContext ac =newClassPathXmlApplicationContext(config);//获取容器中的service对象StudentService service =(StudentService) ac.getBean("studentService");Student student =newStudent(1004,"小六","[email protected]",24);int count = service.addStudent(student);//Spring和mybatis整合在一起使用,事务是自动提交的,无需使用SqlSession.commit();System.out.println(count);}@TestpublicvoidtestServiceSelect(){String config ="applicationContext.xml";ApplicationContext ac =newClassPathXmlApplicationContext(config);//获取容器中的service对象StudentService service =(StudentService) ac.getBean("studentService");List<Student> students = service.queryStudents();for(Student stu : students){System.out.println("stu==== "+ stu);}}}

五、Spring事务

5.1、Spring的事务管理

1、事务是一系列的操作步骤,多个sql语句的集合。

2、在什么时候想到使用事务:当我的操作涉及多个表,或者是多个sql语句的insert、update、delete。需要保证这些语句都是成功才能完成我的功能,或者都失败,保证操作是符合要求的。

在程序中事务是放在service类的方法上面的,因为在service方法里面会使用多个dao,执行多个sql语句。

3、JDBC访问数据库,处理事务 Connection conn; conn.commit(); conn.rollback();

​ Mybatis访问数据库,处理事务,SqlSession.commit(); SqlSession.rollback();

​ Hibernate()访问数据库,处理事务,Session.commit(); SqlSession.rollback();

​ 以上中事务的处理方式的不足之处:

  • 不同的数据库访问技术,处理事务的对象,方法不同,需要了解不同数据库访问技术使用事务的原理
  • 掌握多种数据库中事务的处理逻辑。什么时候提交事务,什么时候回滚事务
  • 处理事务的多种方法

总结:就是多种数据库的访问技术,有不同的事务处理的机制,对象,方法。

4、解决方法

​ Spring提供一种处理事务的统一模型,能使用统一步骤、方式完成多种不同数据库访问技术的事务处理。

​ 使用Spring的事务处理机制,可以完成mybatis访问数据库的事务处理

​ 使用Spring的事务处理机制,可以完成Hibernate访问数据库的事务处理。

5.1.1、处理事务需要怎么做,做什么

​ Spring处理事务的模型,使用的步骤都是固定的。把事务使用的信息提供给Spring就可以了。

​ 1、事务内部提交、回滚事务,使用的事务管理器对象,代替程序员完成commit、rollback。事务管理器是一个接口和它的众多实现类。接口:PlatformTransactionManager,定义了事务重要方法commit,rollback。实现类:Spring把每一种数据库访问技术对应的事务处理类都创建好了。Mybatis访问数据库----Spring创建好的是DataSourceTransactionManager,Hibernate访问数据库—Spring创建好的是HibernateTransactionManager。

​ 如何使用:需要告诉Spring用的是哪种数据库的访问技术

​ 声明数据库访问技术对于的事务管理器实现类,在Spring的配置文件中使用<bean>声明就可以了。例如你要使用mybatis访问数据库,你应该在xml配置文件中 <bean id= “‘xxx’” class="…DataSourceTransactionManager">

​ 2、你的业务方法需要什么样的事务,说明需要事务的类型。

​ 说明方法需要的事务:

(1)事务的隔离级别:有四个值

​ DEFAULT:采用DB默认的事务隔离级别。Mysql的默认为REPEATABLE_READ; Oracle默认为 READ_COMMITTED.

​ READ_UNCOMMITTED:读未提交。未解决任何并发问题。

​ READ_COMMITTED:读已提交。解决脏读,存在不可重复读与幻读。

​ REPEATABLE_READ:可重复读。解决脏读、不可重复读,存在幻读。

​ SERIALIZABLE:串行化。不存在并发问题。

(2)事务的超时时间:表示一个方法执行的最长时间,如果方法执行时超过了时间,事务就回滚。单位是秒,整数值,默认是-1

(3)事务的传播行为:控制业务方法是不是有事务的,是什么样的事务的,7个传播行为,表示你的业务方法调用时,事务在方法之间是如何使用的。

​ PROPAGATION_REQUIRED

指定的方法必须在事务内执行。若当前存在事务,就加入到当前事务中;若当前没有事务,则创建一个新事物。这种传播行为是最常见的选择,也是Spring默认的事务传播行为。如该传播行为加在doOther()方法上。若doSome()在调用doOther()方法时就是在事务内运行的,则doOther()方法的执行也加入到该事务内执行。若doSome()方法在调用doOther()方法时没有在事务内执行,则doOther()方法会创建一个事务,并在其中执行。

​ PROPAGATION_REQUIRES_NEW

总是新建一个事务,若当前存在事务,就将当前事务挂起,直到新事物执行完毕。

​ PROPAGATION_SUPPORTS

指定的方法支持当前事务,但若当前没有事务,也可以以非事务方式执行。

在这里插入图片描述

​ 这三个需要掌握的!

​ 3、提交事务,回滚事务的时机

​ (1)当你的业务方法,执行成功,没有异常抛出,当方法执行完毕,spring在方法执行后提交事务。调用事务管理器的commit

​ (2)当你的业务方法抛出运行时异常或ERROR,spring执行回滚,调用事务管理器的rollback。运行时异常的定义:RuntimeException和它的子类都是运行时异常,例如NullPointException等。

​ (3)当你的业务方法抛出编译异常时,提交事务。不过对于编译时异常,程序员也可以手工设置其回滚方式。

总结Spring的事务:

​ 1、管理事务的是:事务管理器和它的实现类

​ 2、spring的事务是一个统一模型

​ (1)指定要使用的事务管理器实现类,使用<bean>

​ (2)指定哪些类,哪些方法需要加入事务的功能

​ (3)指定方法需要的隔离级别,传播行为,超时

你需要告诉spring,你的项目中类的信息,方法的名称,方法的事务传播行为。

5.2、Spring框架中提供的事务处理方案

5.2.1、适合中小项目使用的,注解方案

Spring框架自己用AOP实现给业务方法增加事务的功能,使用@Transactional注解增加事务。@Transactional注解是Spring框架自己的注解,放在public方法的上面,表示当前方法具有事务。可以给注解的属性赋值,表示具体的隔离级别,传播行为,异常信息等

使用@Transactional的步骤:

1、需要声明事务管理器对象

​ <bean id=“xxx” class=“DataSourceTransactionManager”>

2、开启事务注解驱动,告诉spring框架,使用注解的方式管理事务

spring使用aop机制,创建@Transactional所在的类代理对象,给方法加入事务的功能。Spring给业务方法加入事务:在你的业务方法执行之前,先开启事务,在业务方法之后提交或回滚事务,使用aop的环绕通知

3、在你的方法的上面加入@Transactional

举例:

先创建两个数据库表 sales
在这里插入图片描述
goods
在这里插入图片描述

实现步骤:
1、新建maven
2、加入maven依赖
    1)spring依赖
    2)mybatis依赖
    3)mysql驱动
    4)spring的事务的依赖
    5)mybatis和spring集成的依赖:mybatis官方提供的,用来在spring中创建mybatis的SqlSessionFactory,dao对象的
3、创建实体类
    Sale,Goods
4、创建dao接口和mapper文件
    SaleDao接口,Goods接口
    SaleDao.xml,GoodsDao.xml
5、创建mybatis主配置文件
6、创建service接口和实现类,属性是saleDao,goodsDao
7、创建spring的配置文件:声明mybatis的对象交给spring创建
    1)数据源
    2)SqlSessionFactory
    3)Dao对象
    4)声明自定义的service
8、创建测试类,获取service对象,通过service调用dao完成数据库的访问

实体类:

publicclassSale{privateInteger id;privateInteger gid;privateInteger nums;//setter、getter}publicclassGoods{privateInteger id;privateString name;privateInteger amount;privateFloat price;//setter、getter}

dao接口和mapper文件

publicinterfaceSaleDao{//增加销售记录intinsertSale(Sale sale);}publicinterfaceGoodsDao{//更新库存//goods表示本次用户购买的商品信息,id,购买数量intupdateGoods(Goods goods);//查询商品的信息GoodsselectGoods(Integer id);}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.dao.SaleDao"><insertid="insertSale">
        insert into sale(gid,nums) value(#{gid},#{nums})
    </insert></mapper>
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.dao.GoodsDao"><selectid="selectGoods"resultType="com.domain.Goods">
     select id,name,amount,price from goods where id=#{gid}
    </select><updateid="updateGoods">
        update goods set amount = amount - #{amount} where id = #{id}
    </update></mapper>

mybatis主配置文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!--设置别名--><typeAliases><!--name:实体类所在的包名。这个包下所有类的类名就是别名--><packagename="com.domain"/></typeAliases><!--sql映射文件的位置--><mappers><!--name是包名,这个包中的所有mapper.xml一次都能加载--><packagename="com.dao"/></mappers></configuration>

service接口和实现类

publicinterfaceBuyGoodsService{/**
     * 购买商品的方法
     * @param goodsId 购买商品的编号
     * @param nums 购买的数量
     */voidbuy(Integer goodsId,Integer nums);}
publicclassBuyGoodsServiceImplimplementsBuyGoodsService{privateSaleDao saleDao;privateGoodsDao goodsDao;publicvoidsetSaleDao(SaleDao saleDao){this.saleDao = saleDao;}publicvoidsetGoodsDao(GoodsDao goodsDao){this.goodsDao = goodsDao;}/**
     * rollbackFor:表示发送指定的异常一定回滚
     *//*@Transactional(
            propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            readOnly = false,
            rollbackFor = {
                    NullPointerException.class,NotEnoughException.class
            }
    )*///使用的是事务控制的默认值,默认的传播行为是REQUIRED,默认的隔离级别是DEFAULT//默认抛出运行时异常,回滚事务//@Transactional要用在公共方法之上@Transactional@Overridepublicvoidbuy(Integer goodsId,Integer nums){//记录销售的信息,向sale表添加记录Sale sale =newSale();
        sale.setGid(goodsId);
        sale.setNums(nums);
        saleDao.insertSale(sale);//更新库存Goods goods = goodsDao.selectGoods(goodsId);if(goods ==null){//商品不存在thrownewNullPointerException("编号是: "+goodsId+",商品不存在");}elseif(goods.getAmount()< nums){//商品库存不足thrownewNotEnoughException("编号是: "+goodsId+",商品库存不足");}//修改库存了Goods buyGoods =newGoods();
        buyGoods.setId(goodsId);
        buyGoods.setAmount(nums);
        goodsDao.updateGoods(buyGoods);}}

再写个异常类:

publicclassNotEnoughExceptionextendsRuntimeException{//自定义的运行时异常类publicNotEnoughException(){super();}publicNotEnoughException(String message){super(message);}}

创建JDBC属性配置文件:

jdbc.url=jdbc:mysql://localhost:3306/数据库名
jdbc.username=用户名
jdbc.password=密码

创建spring配置文件:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd"><!--要把数据库的配置信息,写在一个独立的配置文件中,编译修改数据库的配置内容
        要让spring知道配置文件的位置
    --><context:property-placeholderlocation="classpath:jdbc.properties"/><!--声明数据源DataSource,作用是连接数据库的--><beanid="myDataSource"class="com.alibaba.druid.pool.DruidDataSource"init-method="init"destroy-method="close"><!--set注入给DruidDataSource提供连接数据库信息--><!--使用属性配置文件中的数据,语法: ${key}--><propertyname="url"value="${jdbc.url}"/><!--对应的是setUrl()--><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></bean><!--声明mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!--set注入,把数据库连接池赋给了dataSource属性--><propertyname="dataSource"ref="myDataSource"/><!--mybatis主配置文件的位置
            configLocation属性是Resource类型,读取配置文件的
            它的赋值,使用value,指定文件路径,使用classpath:表示文件的位置
        --><propertyname="configLocation"value="classpath:mybatis.xml"/></bean><!--创建dao对象,使用SqlSession的getMapper(StudentDao.class)
        MapperScannerConfigurer:在内部使用getMapper()生成每个dao接口的代理对象。
    --><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--指定SqlSessionFactory对象的id--><propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/><!--指定包名,包名是dao接口所在的类名
            MapperScannerConfigurer会扫描这个包中所有的接口,把每个接口都
            执行一次getMapper()方法,得到每个接口的dao对象
            创建好的dao对象放到spring容器中的,dao对象的默认名称是:接口名首字母小写
        --><propertyname="basePackage"value="com.dao"/></bean><!--声明service--><beanid="buyService"class="com.service.impl.BuyGoodsServiceImpl"><propertyname="goodsDao"ref="goodsDao"/><propertyname="saleDao"ref="saleDao"/></bean><!--使用Spring的事务处理--><!--声明事务管理器--><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--连接的数据库,指定数据源--><propertyname="dataSource"ref="myDataSource"/></bean><!--开启事务注解驱动,告诉spring使用注解管理事务,创建代理对象
        transaction-manager:事务管理器对象的id
    --><tx:annotation-driventransaction-manager="transactionManager"/></beans>

测试类测试执行结果

publicclassMyTest{@Testpublicvoidtest01(){String config ="applicationContext.xml";ApplicationContext ac =newClassPathXmlApplicationContext(config);//从容器中获取service对象BuyGoodsService service =(BuyGoodsService) ac.getBean("buyService");System.out.println("service是代理: "+service.getClass().getName());//调用方法//service.buy(1001,10);//service.buy(1005,10);//service.buy(1001,1000);//执行到这块,数据库编号变为7了,因为id用的是自动递增,所以5,6操作在执行过程中已经//用过了,所以不会在用,因为抛出异常采取了回滚,所以数据库中没有记录//service.buy(1001,10);
        service.buy(1001,100);}}

5.2.2、适合大型项目,使用AspectJ框架功能

在大型项目中,有很多类、方法,需要大量的配置事务,使用AspectJ框架功能,在Spring配置文件中声明类,方法需要的事务。这种方式业务方法和事务配置完全分离

实现步骤:都是在xml配置文件中实现

1、要使用的是aspectj框架,需要在Maven的pom.xml中加入它的依赖

2、声明事务管理器对象

<bean id=“xx” class=“DataSourceTransactionManager”>

3、声明方法需要的事务类型(配置方法的事务属性[隔离级别、传播行为,超时])

4、配置aop:指定哪些类要创建代理

上面例子中只需要改下service实现类和Spring的属性配置文件

publicclassBuyGoodsServiceImplimplementsBuyGoodsService{privateSaleDao saleDao;privateGoodsDao goodsDao;publicvoidsetSaleDao(SaleDao saleDao){this.saleDao = saleDao;}publicvoidsetGoodsDao(GoodsDao goodsDao){this.goodsDao = goodsDao;}@Overridepublicvoidbuy(Integer goodsId,Integer nums){//记录销售的信息,向sale表添加记录Sale sale =newSale();
        sale.setGid(goodsId);
        sale.setNums(nums);
        saleDao.insertSale(sale);//更新库存Goods goods = goodsDao.selectGoods(goodsId);if(goods ==null){//商品不存在thrownewNullPointerException("编号是: "+goodsId+",商品不存在");}elseif(goods.getAmount()< nums){//商品库存不足thrownewNotEnoughException("编号是: "+goodsId+",商品库存不足");}//修改库存了Goods buyGoods =newGoods();
        buyGoods.setId(goodsId);
        buyGoods.setAmount(nums);
        goodsDao.updateGoods(buyGoods);}}
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"><!--要把数据库的配置信息,写在一个独立的配置文件中,编译修改数据库的配置内容
        要让spring知道配置文件的位置
    --><context:property-placeholderlocation="classpath:jdbc.properties"/><!--声明数据源DataSource,作用是连接数据库的--><beanid="myDataSource"class="com.alibaba.druid.pool.DruidDataSource"init-method="init"destroy-method="close"><!--set注入给DruidDataSource提供连接数据库信息--><!--使用属性配置文件中的数据,语法: ${key}--><propertyname="url"value="${jdbc.url}"/><!--对应的是setUrl()--><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></bean><!--声明mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!--set注入,把数据库连接池赋给了dataSource属性--><propertyname="dataSource"ref="myDataSource"/><!--mybatis主配置文件的位置
            configLocation属性是Resource类型,读取配置文件的
            它的赋值,使用value,指定文件路径,使用classpath:表示文件的位置
        --><propertyname="configLocation"value="classpath:mybatis.xml"/></bean><!--创建dao对象,使用SqlSession的getMapper(StudentDao.class)
        MapperScannerConfigurer:在内部使用getMapper()生成每个dao接口的代理对象。
    --><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--指定SqlSessionFactory对象的id--><propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/><!--指定包名,包名是dao接口所在的类名
            MapperScannerConfigurer会扫描这个包中所有的接口,把每个接口都
            执行一次getMapper()方法,得到每个接口的dao对象
            创建好的dao对象放到spring容器中的,dao对象的默认名称是:接口名首字母小写
        --><propertyname="basePackage"value="com.dao"/></bean><!--声明service--><beanid="buyService"class="com.service.impl.BuyGoodsServiceImpl"><propertyname="goodsDao"ref="goodsDao"/><propertyname="saleDao"ref="saleDao"/></bean><!--声明式事务处理,和源代码完全分离的--><!--声明事务管理器对象--><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><propertyname="dataSource"ref="myDataSource"/></bean><!--声明业务方法它的事务属性(隔离级别,传播行为,超时时间)
        id:自定义名称,表示 <tx:advice> 和 </tx:advice>之间的配置内容的
        transaction-manager:事务管理器对象的id
    --><tx:adviceid="myAdvice"transaction-manager="transactionManager"><!--tx:attributes:配置事务属性--><tx:attributes><!--tx:method:给具体的方法配置事务属性,method可以有多个,分别给不同的方法设置事务属性
                name是方法名称: 1)完整的方法名称,不带有包和类
                              2)方法可以使用通配符,*表示任意字符
                propagation:传播行为,枚举值
                isolation:隔离级别
                rollback-for:你指定的异常类名,全限定类名。发生异常一定回滚
            --><tx:methodname="buy"propagation="REQUIRED"isolation="DEFAULT"rollback-for="java.lang.NullPointerException,com.excep.NotEnoughException"/></tx:attributes></tx:advice><!--配置aop--><aop:config><!--配置切入点表达式,指定哪些包中类,要使用事务,aspectj会创建代理对象--><aop:pointcutid="servicePt"expression="execution(* *..service..*.*(..))"/><!--配置增强器:关联advice和pointcut
            advice-ref:通知,上面tx:advice那里的配置
            pointcut-ref:切入点表达式的id
        --><aop:advisoradvice-ref="myAdvice"pointcut-ref="servicePt"/></aop:config></beans>

由此可见,service类的业务方法并没有发生任何改动,只是在Spring的属性配置文件实现,实现了业务方法和事务属性配置完全分离。

标签: spring java 后端

本文转载自: https://blog.csdn.net/qq_49306008/article/details/122342630
版权归原作者 啊qie! 所有, 如有侵权,请联系我们删除。

“Spring笔记”的评论:

还没有评论