Spring的基本使用

一、Spring的概述

1.1 Spring是什么

Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control:

反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层 Spring

MVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多

著名的第三方框架和类库,逐渐成为使用最多的 Java EE 企业应用开源框架。

1.2 Spring的发展历程

  • 1997 年 IBM 提出了 EJB 的思想

  • 1998 年,SUN 制定开发标准规范 EJB1.0

  • 1999 年,EJB1.1 发布

  • 2001 年,EJB2.0 发布

  • 2003 年,EJB2.1 发布

  • 2006 年,EJB3.0 发布

  • Rod Johnson(spring 之父)

  • Expert One-to-One J2EE Design and Development(2002)

    阐述了 J2EE 使用 EJB 开发设计的优点及解决方案

  • Expert One-to-One J2EE Development without EJB(2004)

    阐述了 J2EE 开发不使用 EJB 的解决方式(Spring 雏形)

  • 2017 年 9 月份发布了 spring 的最新版本 spring 5.0 通用版(GA)

1.3 spring的优势

1.3.1 方便解耦,简单开发

通过 Spring 提供的 IoC 容器,可以将对象间的依赖关系交由 Spring 进行控制,避免硬编码所造

成的过度程序耦合。用户也不必再为单例模式类、属性文件解析等这些很底层的需求编写代码,可

以更专注于上层的应用。

1.3.2 AOP编程的支持

通过 Spring 的 AOP 功能,方便进行面向切面的编程,许多不容易用传统 OOP 实现的功能可以通过 AOP 轻松应付。

1.3.3 声明式事务的支持

可以将我们从单调烦闷的事务管理代码中解脱出来,通过声明式方式灵活的进行事务的管理,提高开发效率和质量。

1.3.4 方便程序的测试

可以用非容器依赖的编程方式进行几乎所有的测试工作,测试不再是昂贵的操作,而是随手可做的事情。

1.3.5 方便集成各种优秀框架

Spring 可以降低各种框架的使用难度,提供了对各种优秀框架(Struts、Hibernate、Hessian、Quartz等)的直接支持。

1.3.6 降低 JavaEE API 的使用难度

Spring 对 JavaEE API(如 JDBC、JavaMail、远程调用等)进行了薄薄的封装层,使这些 API 的使用难度大为降低。

1.3.7 Java 源码是经典学习范例

Spring 的源代码设计精妙、结构清晰、匠心独用,处处体现着大师对 Java 设计模式灵活运用以及对 Java 技术的高深造诣。它的源代码无意是 Java 技术的最佳实践的范例。

1.4 Spring的体系结构

二、程序的耦合

2.1 耦合

复制代码
耦合性(Coupling),也叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调
用模块的方式以及通过界面传送数据的多少。模块间的耦合度是指模块之间的依赖关系,包括控制关系、调用关
系、数据传递关系。模块间联系越多,其耦合性越强,同时表明其独立性越差( 降低耦合性,可以提高其独立
性)。耦合性存在于各个领域,而非软件设计中独有的,但是我们只讨论软件工程中的耦合。
在软件工程中,耦合指的就是就是对象之间的依赖性。对象之间的耦合越高,维护成本越高。因此对象的设计
应使类和构件之间的耦合最小。软件设计中通常用耦合度和内聚度作为衡量模块独立程度的标准。划分模块的一个
准则就是高内聚低耦合。
它有如下分类:
(1)内容耦合。当一个模块直接修改或操作另一个模块的数据时,或一个模块不通过正常入口而转入另
一个模块时,这样的耦合被称为内容耦合。内容耦合是最高程度的耦合,应该避免使用之。
(2)公共耦合。两个或两个以上的模块共同引用一个全局数据项,这种耦合被称为公共耦合。在具有大
量公共耦合的结构中,确定究竟是哪个模块给全局变量赋了一个特定的值是十分困难的。
(3) 外部耦合 。一组模块都访问同一全局简单变量而不是同一全局数据结构,而且不是通过参数表传
递该全局变量的信息,则称之为外部耦合。
(4) 控制耦合 。一个模块通过接口向另一个模块传递一个控制信号,接受信号的模块根据信号值而进
行适当的动作,这种耦合被称为控制耦合。
(5)标记耦合 。若一个模块 A 通过接口向两个模块 B 和 C 传递一个公共参数,那么称模块 B 和 C 之间
存在一个标记耦合。
(6) 数据耦合。模块之间通过参数来传递数据,那么被称为数据耦合。数据耦合是最低的一种耦合形
式,系统中一般都存在这种类型的耦合,因为为了完成一些有意义的功能,往往需要将某些模块的输出数据
作为另一些模块的输入数据。
(7) 非直接耦合 。两个模块之间没有直接关系,它们之间的联系完全是通过主模块的控制和调用来实
现的。
总结:
耦合是影响软件复杂程度和设计质量的一个重要因素,在设计上我们应采用以下原则:如果模块间必须
存在耦合,就尽量使用数据耦合,少用控制耦合,限制公共耦合的范围,尽量避免使用内容耦合。
内聚与耦合
内聚标志一个模块内各个元素彼此结合的紧密程度,它是信息隐蔽和局部化概念的自然扩展。内聚是从
功能角度来度量模块内的联系,一个好的内聚模块应当恰好做一件事。它描述的是模块内的功能联系。
耦合是软件结构中各模块之间相互连接的一种度量,耦合强弱取决于模块间接口的复杂程度、进入或
访问一个模块的点以及通过接口的数据。 程序讲究的是低耦合,高内聚。就是同一个模块内的各个元素
之间要高度紧密,但是各个模块之间的相互依存度却要不那么紧密。
内聚和耦合是密切相关的,同其他模块存在高耦合的模块意味着低内聚,而高内聚的模块意味着该模块同他
模块之间是低耦合。在进行软件设计时,应力争做到高内聚,低耦合。

2.2 解决耦合的思路

复制代码
Class.forName("com.mysql.jdbc.Driver");//此处只是一个字符串


此时的好处是,我们的类中不再依赖具体的驱动类,此时就算删除 mysql 的驱动 jar 包,依然可以编译
(运行就不要想了,没有驱动不可能运行成功的)。
同时,也产生了一个新的问题,mysql 驱动的全限定类名字符串是在 java 类中写死的,一旦要改还是要修改
源码。
解决这个问题也很简单,使用配置文件配置。

2.3 工厂模式解耦

复制代码
在实际开发中我们可以把三层的对象都使用配置文件配置起来,当启动服务器应用加载的时候,
让一个类中的方法通过读取配置文件,把这些对象创建出来并存起来。在接下来的使用的时候,
直接拿过来用就好了。
那么,这个读取配置文件,创建和获取三层对象的类就是工厂。

工厂类:

复制代码
public class BeanFactory {
    private static Properties properties;
    //创建单例的容器,用于存储要创建的bean对象
    private static Map<String,Object> beans;
    static {
        try {
            properties = new Properties();
            //加载配置文件
            properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
            //实例化map容器
            beans = new HashMap<String, Object>();
            //获取properties的所有keys
            Set<Object> keys = properties.keySet();
            //遍历key
            for (Object o : keys) {
                //强转为String类型
                String key = (String)o;
                //获取properties集合key对应的全限定类名
                String beanPath = properties.getProperty(key);
                //使用反射技术创建对象
                Object bean = Class.forName(beanPath).newInstance();
                //将创建的对象存储到beans容器
                beans.put(key,bean);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 此方法是使用单利模式创建所对应的对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
        return beans.get(beanName);
    }
    
    /**
     * 根据bean的名称获取对象  此方法创建的是多例模式
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName)  {
        Object bean = null;
        try {
            String beanPath = properties.getProperty(beanName);
            bean = Class.forName(beanPath).newInstance();
            return bean;
        }catch (Exception e){

        }
        return bean;
    }

}

配置文件

复制代码
	AccountServiceImpl=com.service.impl.AccountServiceImpl
AccountDaoImpl=com.dao.impl.AccountDaoImpl

创建对象

复制代码
IAccountService accountService = (IAccountService) BeanFactory.getBean("AccountServiceImpl");
IAccountDao dao = (IAccountDao)BeanFactory.getBean("AccountDaoImpl");

2.4 IOC 控制反转

2.4.1控制反转

****(Inversion of Control,缩写为IoC)是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫"依赖查找"(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。

2.4.2 IOC的作用

IOC是削减程序之间的耦合度,而不能完全消除。

我们普通的通过new的方式获取对象

使用工厂模式创建对象

2.5 Bromon的blog上对IoC与DI浅显的讲解

IoC(控制反转)

首先想说说IoC(Inversion of Control,控制反转)。这是spring的核心,贯穿始终。所谓IoC,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系。这是什么意思呢,举个简单的例子,我们是如何找女朋友的?常见的情况是,我们到处去看哪里有长得漂亮身材又好的mm,然后打听她们的兴趣爱好、qq号、电话号、ip号、iq号.........,想办法认识她们,投其所好送其所要,然后嘿嘿......这个过程是复杂深奥的,我们必须自己设计和面对每个环节。传统的程序开发也是如此,在一个对象中,如果要使用另外的对象,就必须得到它(自己new一个,或者从JNDI中查询一个),使用完之后还要将对象销毁(比如Connection等),对象始终会和其他的接口或类藕合起来。

那么IoC是如何做的呢?有点像通过婚介找女朋友,在我和女朋友之间引入了一个第三者:婚姻介绍所。婚介管理了很多男男女女的资料,我可以向婚介提出一个列表,告诉它我想找个什么样的女朋友,比如长得像李嘉欣,身材像林熙雷,唱歌像周杰伦,速度像卡洛斯,技术像齐达内之类的,然后婚介就会按照我们的要求,提供一个mm,我们只需要去和她谈恋爱、结婚就行了。简单明了,如果婚介给我们的人选不符合要求,我们就会抛出异常。整个过程不再由我自己控制,而是有婚介这样一个类似容器的机构来控制。Spring所倡导的开发方式就是如此,所有的类都会在spring容器中登记,告诉spring你是个什么东西,你需要什么东西,然后spring会在系统运行到适当的时候,把你要的东西主动给你,同时也把你交给其他需要你的东西。所有的类的创建、销毁都由 spring来控制,也就是说控制对象生存周期的不再是引用它的对象,而是spring。对于某个具体的对象而言,以前是它控制其他对象,现在是所有对象都被spring控制,所以这叫控制反转。

DI(依赖注入)

IoC的一个重点是在系统运行中,动态的向某个对象提供它所需要的其他对象。这一点是通过DI(Dependency Injection,依赖注入)来实现的。比如对象A需要操作数据库,以前我们总是要在A中自己编写代码来获得一个Connection对象,有了 spring我们就只需要告诉spring,A中需要一个Connection,至于这个Connection怎么构造,何时构造,A不需要知道。在系统运行时,spring会在适当的时候制造一个Connection,然后像打针一样,注射到A当中,这样就完成了对各个对象之间关系的控制。A需要依赖 Connection才能正常运行,而这个Connection是由spring注入到A中的,依赖注入的名字就这么来的。那么DI是如何实现的呢? Java 1.3之后一个重要特征是反射(reflection),它允许程序在运行的时候动态的生成对象、执行对象的方法、改变对象的属性,spring就是通过反射来实现注入的。

理解了IoC和DI的概念后,一切都将变得简单明了,剩下的工作只是在spring的框架中堆积木而已。

三、使用Spring的IOC解决程序的耦合

3.1 Spring的入门案例

meaven的依赖配置文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="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.github</groupId>
    <artifactId>SpringDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>
</project>

service业务层

复制代码
public class UserServiceImpl implements IUserService {
    public void saveUser() {
        System.out.println("用户已经保存");
    }
}

配置bean文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--class是创建类的全限定类名-->
    <bean id="userService" class="service.impl.UserServiceImpl"></bean>
</beans>

测试

复制代码
public class SpringTest01 {

    public static void main(String args[]){
		//获取SpringIOC的核心容器,并根据id获取对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IUserService userService = (IUserService)ac.getBean("userService");
        userService.saveUser();

    }
}

3.2 Spring基于xml的IOC细节

3.2.1 Spring中工厂的类结构图
3.2.2 BeanFactory和Application的区别
复制代码
    BeanFactory 才是 Spring 容器中的顶层接口。
    ApplicationContext 是它的子接口。

        BeanFactory 和 ApplicationContext 的区别:
        创建对象的时间点不一样。
        ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。用于创建单例模式
        BeanFactory:什么使用什么时候创建对象。用于创建多例模式
3.2.3 ApplicationContext的三个常用类
复制代码
ApplicationContext的三个常用类:
ClassPathXmlApplicationContext(String configLocation):
他可以加载类路径下的配置文件,要求配置文件是在类路径下,不在的话加载不了(常用)
FileSystemXmlApplicationContext(String configLocation)
他可以加载磁盘上任意位置上面的配置文件(要有访问权限)
AnnotationConfigApplicationContext:
他可以读取注解创建容器

3.3 IOC中xml管理的细节

创建bean的方式有三种

3.3.1 bean标签
复制代码
    作用:
    用于配置对象让 spring 来创建的。
    默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。
    属性:
    id:给对象在容器中提供一个唯一标识。用于获取对象。
    class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
    scope:指定对象的作用范围。

        singleton :默认值,单例的.
        prototype :多例的.
        request :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
        session :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中.
        global session(集群) :WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么globalSession 相当于 session
        init-method:指定类中的初始化方法名称。
        destroy-method:指定类中销毁方法名称。
3.3.2 bean 的作用范围和生命周期
复制代码
单例对象:scope="singleton"
一个应用只有一个对象的实例。它的作用范围就是整个引用。
生命周期:
对象出生:当应用加载,创建容器时,对象就被创建了。
对象活着:只要容器在,对象一直活着。
对象死亡:当应用卸载,销毁容器时,对象就被销毁了。
多例对象:scope="prototype"
每次访问对象时,都会重新创建对象实例。
生命周期:
对象出生:当使用对象时,创建新的对象实例。
对象活着:只要对象在使用中,就一直活着。
对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。
3.3.3 创建bean的三种方式
  • 方式一:使用默认构造函数进行创建

    在Spring的配置文件中使用bean标签,配置id和class之后,没有其他属性和标签时,

    采用的就是默认构造函数创建bean对象,此时类中如果没有空参构造方法,则无法创建对象

    <bean id="accountService" class="com.service.impl.AccountServiceImpl"></bean>

  • 方式二:spring 管理实例工厂-使用实例工厂的方法创建对象

使用某个类中的方法创建并存入Spring的IOC容器中,这种方式一般是存在于jar包中使用实例方法创建对象的方式。

复制代码
/**
 *  模拟一个工厂类(该类可能存在于jar包中,我们无法通过修改源码的方式来提供构造函数)
 * @param
 * @return
 */
public class InstanceFactory {
    public IAccountService getIAccountService(){
        return new AccountServiceImpl();
    }
}

<bean id="instanceFactory" class="com.factory.InstanceFactory"></bean>
    <bean id="accountService" factory-bean="instanceFactory" factory-method="getIAccountService"></bean>

此种方式是先把工厂的创建交给 spring 来管理。然后再使用工厂的 bean 来调用里面的方法

factory-bean 属性:用于指定实例工厂 bean 的 id。

factory-method 属性:用于指定实例工厂中创建对象的方法。

  • 方式三:spring 管理静态工厂-使用静态工厂的方法创建对象

使用某个类中的方法创建并存入Spring的IOC容器中,这种方式一般是存在于jar包中使用静态方法创建对象的方式

复制代码
/**
 *  模拟一个工厂类,使用静态方法创建IAccountService对象(该类可能存在于jar包中,我们无法通过修改源码的方式来提供构造函数)
 * @param
 * @return
 */
public class StaticInstanceFactory {

    public static IAccountService getIAccountService(){
        return new AccountServiceImpl();
    }
}

<bean id="accountService" class="com.factory.StaticInstanceFactory" factory-method="getIAccountService"></bean>

使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入 spring 容器

id 属性:指定 bean 的 id,用于从容器中获取

class 属性:指定静态工厂的全限定类名

factory-method 属性:指定生产对象的静态方法

3.4 Spring的依赖注入

3.4.1 概念

依赖注入:Dependency Injection。它是 spring 框架核心 ioc 的具体实现。我们的程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。ioc 解耦只是降低他们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。那这种业务层和持久层的依赖关系,在使用 spring 之后,就让 spring 来维护了。简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。

  • 依赖注入:Dependency Injection。它是 spring 框架核心 ioc 的具体实现。我们的程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。ioc 解耦只是降低他们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。那这种业务层和持久层的依赖关系,在使用 spring 之后,就让 spring 来维护了。简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。
3.4.2 依赖注入
复制代码
依赖注入:
Dependency Injection
IOC的作用:
降低程序间的依赖关系即降低耦合
依赖关系的管理:
都交给了Spring来维护
在当前类需要用到其他类的对象,由spring为我们提供,我们只需要在配置文件中说明
依赖关系的维护:
我们就称之为依赖注入
依赖注入:
能注入的数据有三类:
基本数据类型和String
其他的bean类型(在配置文件中或者注解配置过的bean)
复杂类型/集合类型
注入的方式有三种:
第一种:使用构造函数提供
第二种:使用set方法提供
第三种:使用注解提供
3.4.2.1 第一种注入:构造函数注入
复制代码
使用标签constructor-arg
使用出现在bean标签的内部
标签中的属性:
type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引的位置是从0开始的
name:用于指定个构造函数中指定名称的参数赋值(常用)
以上三个用于指定给构造函数中哪个参数赋值===
value:用于提供基本类型和String类型的数据
ref:用于指定的其他bean类型数据,他指的就是在spring的IOC核心容器中出现过的bean对象

​ 优势:在注入数据时,使用者必须要注入数据,否则对象无法创建成功,可以不让使用者遗忘数据的注入
​ 弊端:改变了bean对象的实例化方式,使我们在创建对象时,即使用不到这些数据,也必须注入

public class AccountServiceImpl implements IAccountService {
    private String name;
    private Integer age;
    private Date birthday;
    public AccountServiceImpl(String name,Integer age,Date birthday){
        this.name=name;
        this.age=age;
        this.birthday=birthday;
    }
    /**
     * 保存用户
     */
    @Override
    public void saveAccount() throws Exception{
        System.out.println("service中的saveAccount方法执行了 ");
    }
    @Override
    public String toString() {
        return "AccountServiceImpl{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }
}

<bean id="accountService" class="com.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="test"></constructor-arg>
        <!--Integer类型spring能直接进行类型转型为Integer类型-->
        <constructor-arg name="age" value="18"></constructor-arg>
        <!--java.util.Date类型不能直接进行spring能直接进行转型-->
        <constructor-arg name="birthday" ref="date"></constructor-arg>
    </bean>
    <!--配置一个日期对象,将来用于引用-->
    <bean id="date" class="java.util.Date"></bean>
3.4.1.2 第二种注入:set方法注入
复制代码
第二种:set方法注入 (更常用的方式 )
使用的标签是property
使用在bean标签的内部
标签的属性:
name:找用于指定注入时所调用的set方法名称
value:用于提供基本类型和String类型的数据
ref:用于指定的其他bean类型数据,他指的就是在spring的IOC核心容器中出现过的bean对象
优势:创建对象时,没有明确限制
劣势:如果有某成员必须有值,则容易造成遗忘

<bean id="accountService2" class="com.service.impl.AccountServiceImpl2">
        <property name="name" value="test02"></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="date2"></property>
    </bean>
    <!--配置一个日期对象,将来用于引用-->
    <bean id="date2" class="java.util.Date"></bean>

/**
 * 账户的业务层实现类
 * @param
 * @return
 */
public class AccountServiceImpl2 implements IAccountService {
    private String name;
    private Integer age;
    private Date birthday;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    /**
     * 保存用户
     */
    @Override
    public void saveAccount() throws Exception{
        System.out.println("service2中的saveAccount方法执行了 ");
    }

    @Override
    public String toString() {
        return "AccountServiceImpl{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }
}
3.4.1.3 第三种注入:注入集合属性
复制代码
用于给集合结构注入的标签
list array set
用于给map结构注入的标签
map property
结构相同的时候,可以任意使用,开发中一般都用set和map则这两种结构

<bean id="accountService3" class="com.service.impl.AccountServiceImpl3">
        <!--注入数组-->
        <property name="myStrs">
            <array>
                <!--数组中的元素-->
                <value>a</value>
                <value>b</value>
                <value>c</value>
            </array>
        </property>

        <!--注入list集合-->
        <property name="myList">
            <list>
                <value>d</value>
                <value>e</value>
                <value>f</value>
            </list>
        </property>

        <!--注入set集合-->
        <property name="mySet">
            <set>
                <value>g</value>
                <value>h</value>
                <value>i</value>
            </set>
        </property>

        <!--注入map集合-->
        <property name="myMap">
            <map>
                <!--map集合的映射方式1-->
                <entry key="k1" value="张三"></entry>
                <!--map集合的映射方式2-->
                <entry key="k2">
                    <!--value表示值的类型-->
                    <value type="java.lang.String">李四</value>
                </entry>
            </map>
        </property>

        <property name="myPros">
            <props>
                <prop key="p1">这是p1的内容</prop>
                <prop key="p2">这里p2的内容</prop>
            </props>
        </property>
    </bean>

/**
 * 账户的业务层实现类
 * @param
 * @return
 */
public class AccountServiceImpl3 implements IAccountService {
    private String[] myStrs;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String,String> myMap;
    private Properties myPros;

    public String[] getMyStrs() {
        return myStrs;
    }

    public void setMyStrs(String[] myStrs) {
        this.myStrs = myStrs;
    }

    public List<String> getMyList() {
        return myList;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public Set<String> getMySet() {
        return mySet;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public Map<String, String> getMyMap() {
        return myMap;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public Properties getMyPros() {
        return myPros;
    }

    public void setMyPros(Properties myPros) {
        this.myPros = myPros;
    }

    @Override
    public void saveAccount() throws Exception {
        System.out.println("save方法执行");
        System.out.println(Arrays.toString(myStrs));
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myPros);
    }

四、基于注解的IOC配置

4.1、xml的基本配置

使用注解配置需要在bean.xml 文件引入xmlns依赖,并且需要告知Spring容器在创建的时候要扫描的包,配置所需的标签不是bean的约束中,而是一个名为context名称空间和约束中

复制代码
<context:component-scan base-package="com.github"></context:component-scan>

4.2 常用注解

4.2.1 用于加载对象进入IOC容器的注释

他们的作用和使用xml配置配置文件的标签功能是一致的
@Component

复制代码
作用:用于把当前对象存入到Spring的IOC容器中

​ 属性:

​ value:用于指定bean的id,默认为当前类型且首字母小写

@Controlle

复制代码
作用:和@Component标签的作用一致,spring用于区分三层架构的表现层

@Service

复制代码
作用:和@Component标签的作用一致,spring用于区分三层架构的业务层

@Repositor

复制代码
作用:和@Component标签的作用一致,spring用于区分三层架构的持久层

以上三个注解他们的作用和属性和Component是一致的

他们三个是Spring框架为我们提供明确的使用三层架构使用的注解,使我们的三层架构更加清晰

4.2.2 用于注入数据的注解

他们的作用和xml配置文件中的bean标签中的标签的作用是一致的

@Autowried

复制代码
一般出现在变量和方法中

作用:

自动按照类型注入,只要容器中有唯一的bean对象类型和要注入的变量类型匹配,就可以注入成功,

如果IOC容器没有任何bean的类型和要注入的变量类型匹配则报错

如果IOC容器中有多个 bean的类型相同时,先圈定出这些对象,再根据注入变量的变量名去和IOC容器中的 
key进行匹配,如果都没有匹配上,则报错

细节:

使用注解方式注入set方法就不是必须的了

@Qualifier

复制代码
作用:在按照类型注入的基础之上再按照名称注入,它在给类成员注入时不能单独使用,在给方法参数注入时可以单独使用

@Resource

复制代码
作用:直接按照bean的id注入,他可以直接使用

属性:

​ name:用于指定bean的id

以上三个注解只能注入其他类型bean类型的数据,而基本类型和String类型无法使用上述注解实现,另外,集合类型的注入只能通过xml配置的形式来实现
@value

复制代码
作用:用于注入基本数据类型和String类型

属性:

​ value:用于指定数据的值,它可以使用Spring中的SpEL(Spring的EL表达式)

​ SpEL的写法:$

//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao2")
    private IAccountDao accountDao = null;
4.2.3 用于改变作用范围的注释

他们的作用和标签中的scope属性实现的功能一致

@Scope

复制代码
作用:用于指定bean的作用范围

属性:

​ value:用于指定作用范围,常取值为:singleton(单例,默认值) prototype(多例)
4.2.4 用于生命周期的注释

@PreDestroy

复制代码
作用:用于指定销毁方法

细节:多例对象没有销毁方法,多例对象是长时间不使用后由java的垃圾回收机制回收

@PosConstruct

复制代码
作用:用于指定初始化方法

@Component("accountService")
//@Scope("singleton")//创建的是单例对象,Spring默认的
//@Scope("prototype")//创建的是多例对象,
public class AccountServiceImpl implements IAccountService {
//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao2")
    private IAccountDao accountDao = null;

    /**
     * 保存用户
     */
    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }

    @PostConstruct//声明是初始化方法
    public void init(){
        System.out.println("初始化方法执行");
    }

    @PreDestroy//声明是销毁方法
    public void destroy(){
        System.out.println("销毁方法执行");
    }
}

4.3高级注解

@Configuration

复制代码
作用:

​ 指定当前类是一个配置类

细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可不写

@ComponentScan

复制代码
作用:

​ 通过注解指定Spring需要扫描的包

属性:

​ value:和xml的context:component-scan basePackages的作用是一致的,都是用于指定创建容器时
要扫描的包,我们使用此注解相当于用xml配置了
<context:component-scan base-package="com.github"></context:component-scan>

@ComponentScan("com.github")

@Bean

复制代码
作用:用于把当前方法的返回值作为bean对象存入Spring的ioc容器中

属性:

​ name:用于指定bean的id,当不写时,默认为该方法名

细节:当我们使用注解配置的方式,如果方法有参数,Spring会自动去ioc容器中查找有没有可用的bean对象,
查找的方式和Autowired注解的作用是一致的

/**
     * 用于创建一个QueryRunner对象
     *
     * @param ds
     * @return
     */
    @Bean(name = "queryRunner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource ds) {
        return new QueryRunner(ds);
    }

@Import

复制代码
作用:用于导入其他配置类

属性:

​ value:用于指定其他配置类的字节码文件,当我们使用Improt注解后,有Import注解的类就是父配置类,
而导入的是子配置类

@Configuration//标识为配置类
@ComponentScan("com.github")//spring需要扫描的包
@Import(JdbcConfig.class)//指定子配置类
@PropertySource("classpath:jdbc.properties")//指定jdbc.properties文件位置
public class SpringConfiguration {
	
}

4.4 配置properties文件注解

@PropertySource

复制代码
作用:用于指定properties文件的位置

属性:

​ value:指定文件的名称和路径

​ 关键字:classpath:表示类路径下

当使用该配置后,properties文件的内容可以通过SpEL表达式的形式获取

获取方式:

如:@Value("${jdbc.driver}")

@PropertySource("classpath:jdbc.properties")//指定jdbc.properties文件位置

//配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy_spring
jdbc.user=root
jdbc.password=123

@Value("${jdbc.driver}")
private String driver;

@Value("${jdbc.url}")
private String url;

@Value("${jdbc.user}")
private String user;

@Value("${jdbc.password}")
private String password;

4.5 细节

复制代码
当使用纯注解开发的方式时,获取ioc容器不再使用new ClassPathXmlApplicationContext("bean.xml")的方式,
而是采用new AnnotationConfigApplicationContext(SpringConfiguration.class)的方式

五、spring整合Junit

Spring整合junit的配置:

​ 1、导入Spring整合junit的jar或maven的坐标(Spring-test),同时junit的jar包必须是在4.12版本以上

复制代码
<!--配置spring整合junit的jar包-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>

<!--导入junit的jar包,必须是在4.12版本以上-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

​ 2、使用Junit提供的@RunWit注解把junit原有的main方法替换,替换成Spring提供的

​ 3、使用@ContextConfigurtion告知spring的运行器,spring的ioc创建是基于配置文件还是基于注解类,并且说明对应位置

​ @ContextConfiguration的属性:

​ locations:指定xml 文件的位置,注意要加上classpath关键字表示根目录

​ classes:指定注解类所在的位置

复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SpringConfiguration.class)
public class AccountServiceTest {
    //自动注入
    @Autowired
    private IAccountService service;
    @Test
    public void testFindAll() {
        List<Account> accounts = service.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
}

六、基于注解开发的简单账务项目

实体类Account对象

复制代码
package com.github.domain;
import java.io.Serializable;
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Integer money;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getMoney() {
        return money;
    }
    public void setMoney(Integer money) {
        this.money = money;
    }
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

持久层实现类

复制代码
package com.github.dao.impl;

import com.github.dao.IAccountDao;
import com.github.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * @param
 * @return
 */
@Service("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Resource(name = "queryRunner")
    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAll() {
        try {
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findById(Integer accountId) {
        try {
            return runner.query("select * from account where id=?",new BeanHandler<Account>(Account.class),accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money) value(?,?)",account.getName(),account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try {
            runner.update("delete from account where id=?", accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

业务层实现类

复制代码
package com.github.service.impl;

import com.github.dao.IAccountDao;
import com.github.domain.Account;
import com.github.service.IAccountService;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import java.util.List;

/**
 * @param
 * @return
 */
@Controller("accountService")
public class AccountServiceImpl implements IAccountService {
    @Resource(name = "accountDao")
    private IAccountDao dao;

    @Override
    public List<Account> findAll() {
        return dao.findAll();
    }

    @Override
    public Account findById(Integer accountId) {
        return dao.findById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        dao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        dao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer accountId) {
        dao.deleteAccount(accountId);
    }
}

主配置类SpringConfiguration类

复制代码
package config;
import org.springframework.context.annotation.*;
@Configuration//标识为配置类
@ComponentScan("com.github")//需要扫描的包
@Import(JdbcConfig.class)//指定配置类
@PropertySource("classpath:jdbc.properties")//指定properties文件位置
public class SpringConfiguration {

}

子配置JdbcConfig类

复制代码
package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;

/**
 * 配置数据库
 * @param
 * @return
 */
//@Configuration
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.user}")
    private String user;

    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于创建一个QueryRunner对象
     *
     * @param ds
     * @return
     */
    @Bean(name = "queryRunner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource ds) {
        return new QueryRunner(ds);
    }

    /**
     * 创建数据源对象
     *
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(user);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException("数据库连接失败!");
        }
    }
}

jdbc配置文件

复制代码
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy_spring
jdbc.user=root
jdbc.password=123

测试类

复制代码
package com.github.test;
import config.SpringConfiguration;
import com.github.domain.Account;
import com.github.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * @param
 * @return
 */
public class AccountServiceTest {
    @Test
    public void testFindAll() {
//        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //使用注解创建容器
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService service = context.getBean("accountService", IAccountService.class);
        List<Account> accounts = service.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindById() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService service = (IAccountService)context.getBean("accountService");
        Account account = service.findById(2);
        System.out.println(account);
    }

    @Test
    public void testSave() {
//        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //使用注解创建容器
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService service = (IAccountService)context.getBean("accountService");
        Account account = new Account();
        account.setName("test");
        account.setMoney(2000);
        service.saveAccount(account);
    }

    @Test
    public void testUpdate() {
//        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //使用注解创建容器
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService service = (IAccountService)context.getBean("accountService");
        Account account = service.findById(4);
        account.setMoney(3000);
        service.updateAccount(account);

    }@Test
    public void testDelete() {
//        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //使用注解创建容器
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService service = (IAccountService)context.getBean("accountService");
        service.deleteAccount(4);
    }
}

七、AOP的相关概念

7.1 、AOP概述

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

简单的说他就是把我们重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础
上进行已有方法的增强
7.1.2 AOP的作用及优势
复制代码
作用:

​ 在程序运行期间,不修改源码对已有方法进行增强

优势:

​ 减少代码重复率

​ 提高开发效率

​ 维护方便
7.1.3 AOP的实现方式
复制代码
使用动态代理技术
7.2 动态代理
复制代码
特点:字节码随用随调用

作用:在不修改源代码的方式对方法进行增强

分类:基于接口的动态代理、基于子类的动态代理(cglib)
7.2.1 基于接口的动态代理
复制代码
提供者:JDK官方

要求:被代理对象至少实现一个接口

使用方法请阅读代码注释

商品接口

复制代码
/**
 * @param
 * @return
 */
public interface IProducer {

    /**
     * 销售产品
     * @param money
     */
    void saleProduct(float money);

    /**
     * 产品售后
     * @param money
     */
    void afterProduct(float money);
}

商品接口实现类

复制代码
public interface IProducer {

    /**
     * 销售产品
     * @param money
     */
    void saleProduct(float money);

    /**
     * 产品售后
     * @param money
     */
    void afterProduct(float money);
}

消费类,进行方法增强

复制代码
public class Client {
    public static void main(String args[]){
        /**
         * 动态代理:
         *      特点:字节码随用随创建,随用随加载
         *      作用:在不修改源代码的方式对方法进行增强
         *      分类:
         *          基于接口的动态代理
         *          基于子类的动态代理
         *
         *       基于接口的动态代理:
         *             涉及的类:Proxy
         *             提供者:JDK官方
         *             如何创建代理对象:
         *                      使用Proxy的newProxyInstance方法
         *             创建代理对象的要求:
         *                  被代理对象最少实现一个接口,如果没有则不能使用
         *        newProxyInstance方法的参数:
         *              ClassLoader:类加载器
         *                  它用于加载代理对象的字节码的,和被代理对象使用相同的类加载器,固定写法
         *              Class[]:字节码数组
         *                  它是用于让代理对象和被代理对象有相同的方法,固定写法
         *              InvocationHandler:用于提供增强的代码
         *                  它是让我们写代理方法的,我们一般都是写接口的实现类,常写为匿名内部类
         *
         *
         */
        IProducer producer = new Producer();

        //创建代理对象
        IProducer producerProxy = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(), new InvocationHandler() {

            /**
             *   作用:执行被代理对象的任何接口方法都会经过该方法
             * @param proxy 代理对象的引用
             * @param method    当前执行的方法	
             * @param args      当前执行方法所需的参数
             * @return 和被代理对象有相同的返回值
             * @throws Throwable
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object value = null;
                //提供增强的代码
                //1、获取方法执行的参数
                String money_str = args[0].toString();
                float money = Float.parseFloat(money_str);

                //2、判断当前执行方法是不是销售方法
                if (method.getName().equals("saleProduct")) {
                    value = method.invoke(producer, money * 0.8f);

                } else {
                    //不是销售方法,直接执行,方法不增强
                    value = method.invoke(producer,args);
                }
                return value;
            }
        });

        producerProxy.saleProduct(2000f);
    }
}
7.2.2 基于子类实现动态代理
复制代码
提供者:cglib库

要求:被代理的类不是最终类,及被代理的类不能被final修饰

使用方法请阅读代码注释

商品实现类

复制代码
/**
 * 一个生产者
 * @param
 * @return
 */
public class Producer implements IProducer{

    /**
     * 销售产品
     * @param money
     */
    @Override
    public void saleProduct(float money){
        System.out.println("销售产品,并拿到钱:"+money);
    }


    /**
     * 售后
     * @param money
     */
    @Override
    public void afterProduct(float money){
        System.out.println("提供售后服务,并拿到钱"+money);

    }

}

模拟一个消费者

复制代码
/**
 * 模拟一个消费者
 * @param
 * @return
 */
public class Client {
    public static void main(String args[]) {
        /**
         * 动态代理:
         *      特点:字节码随用随创建,随用随加载
         *      作用:在不修改源代码的方式对方法进行增强
         *      分类:
         *          基于子类的动态代理
         *          基于子类的动态代理
         *
         *       基于接口的动态代理:
         *             涉及的类:Enhancer
         *             提供者:第三方cglib库
         *             如何创建代理对象:
         *                      使用Enhancer类的create方法
         *             创建代理对象的要求:
         *                  被代理类不能是最终类:最终类:被final修饰的类
         *        create方法的参数:
         *              Class:指定被代理对象的字节码
         *
         *              Callback:用于提供增强的代码
         *                  它是让我们写如何代理,我们一般都是些一些该接口的实现类,通常情况下都是使用匿		   *                  名内部类
         *                  此接口的实现类一般都是谁用谁写
         *                  我们一般写的都是该接口的子接口实现类:MethodInterceptor
         *
         *
         */

        Producer producer = new Producer();
        Producer productCglib  = (Producer)Enhancer.create(producer.getClass(), new MethodInterceptor() {
            /**
             * 执行被代理对象的方法都经过该方法,用于提供增强代码的
             * @param o  代理对象的引用
             * @param method  当前执行的方法
             * @param objects   当前执行方法所需要的参数
             * @param methodProxy 当前执行方法的代理对象
             * @return
             * @throws Throwable
             */
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                //判断是不是销售方法
                if (method.getName().equals("saleProduct")) {
                    //获取执行方法的参数
                    float money = (float) objects[0];
                    method.invoke(producer, money * 0.8f);
                    return null;
                }
                Object obj = method.invoke(producer, args);
                return obj;
            }
        });
        productCglib.saleProduct(20000f);

    }

}
7.2.3 使用动态代理解决事务问题

connection连接的工具类,用于从数据源获取同一个连接,并实现线程和连接的解绑功能

复制代码
package com.github.utils;
import javax.sql.DataSource;
import java.sql.Connection;

/**
 *
 * connection连接的工具类,用于从数据源中获取一个连接,并且实现和线程的解绑
 * @param
 * @return
 */
public class ConnectionUtils {
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    private DataSource dataSource;

    public void setDataSource(DataSource ds){
        this.dataSource = ds;
    }

    //判断当前线程容器是否有connection连接

    /**
     * 获取连接
     * @return
     */
    public Connection getThreadConnection(){
        Connection conn = null;
        try {
            //从线程容器中获取connection
             conn = threadLocal.get();

            //判断线程容器中是否有连接
            if(conn == null){
                //创建一个连接
                conn = dataSource.getConnection();
                //存入到线程容器
                threadLocal.set(conn);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 将线程和连接解绑:
     *  为什么要解绑:
     *      线程一般存储在线程池中,连接一般存储在连接池中,
     *      当一个连接使用完后将close放到连接池中,此时还绑定在对应的线程中,当线程下次使用时拿到的是一个close的连接对象
     */
    public void removeConnection(){
        threadLocal.remove();
    }
}

执行事务的工具类 TransactionManager

复制代码
package com.github.utils;
import java.sql.SQLException;

/**
 * 执行事务的工具类
 * @param
 * @return
 */
public class TransactionManager {

    private ConnectionUtils connectionUtils;
    public void setConnectionUtils(ConnectionUtils connectionUtils){
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务方法
     */
    public void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 提交事务方法
     */
    public void commit(){
        try {
            connectionUtils.getThreadConnection().commit();
            System.out.println("事务提交");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 事务回滚方法
     */
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
            System.out.println("事务回滚");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 释放连接
     */
    public void release(){
        try {
            //将连接放回池中
            connectionUtils.getThreadConnection().close();
            //将连接和线程解绑
            connectionUtils.removeConnection();
            System.out.println("线程和连接解绑");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

创建service层的代理对象的工厂类

复制代码
package com.github.factory;
import com.github.service.IAccountService;
import com.github.utils.TransactionManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 用于创建service的代理对象的工厂
 * @param
 * @return
 */
public class BeanFactory {

    private IAccountService accountService;
    private TransactionManager manager;

    public void setAccountService(IAccountService accountService){
        this.accountService = accountService;
    }

    public void setManager(TransactionManager manager){
        this.manager = manager;
    }

    /**
     * 获取service的代理对象
     * @return
     */
    public IAccountService getAccountService(){
        return (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            /**
             * 添加事务的支持
             * @param proxy
             * @param method
             * @param args
             * @return
             * @throws Throwable
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object rtValue = null;
                try {
                    System.out.println("使用service代理对象");
                    //开启事务
                    manager.beginTransaction();
                    //执行操作
                    rtValue = method.invoke(accountService, args);
                    //提交事务
                    manager.commit();
                    return rtValue;

                }catch (Exception e){
                    //事务回滚
                    manager.rollback();
                    e.printStackTrace();
                }finally {
                    //解除绑定
                    manager.release();
                }
                return rtValue;

            }
        });
    }

}

八、Spring中的AOP

8.1 spring中的AOP的相关术语和代理选择方式

复制代码
Joinpoint(连接点):

​ 所谓连接点是指那些被拦截的点。在Spring中,这些点指的是方法,因为spring值支持方法类型的连接点

Pointcut(切入点):

​ 所谓切入点是指我们要对哪些Joinpoint进行拦截的定义

Advice(通知/增强)

​ 所谓通知是指拦截到Joinpoint之后所要做的事情就是通知

​ 通知的类型分为:

​ 前置通知(before):在切入点方法执行之前执行

​ 结果通知(affter-returning):在切入点正常执行之后执行

​ 异常通知(after-throwing):在切入点异常执行之后执行

​ 最终通知(after):无论切入点是否正常执行都会执行

Introduction(引介):

​ 引介是一种特殊的通知在不修改类代码的前提下,Introduction可以在运行期间为类动态添加一些方法或Field

Target(对象目标):代理的目标对象

Weaving(织入):是把增强引用到目标对象来创建新的代理对象的过程,Spring采用动态代理织入,
而Aspectj采用编译期织入和类装载期织入

Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类

Aspect(切面):是切入点和通知(引介)的结合

在 spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。

8.2 Spring中基于注解的AOP配置

复制代码
spring基于xml配置AOP的步骤
1、把通知类Logger也交给spring来管理
2、使用aop:config标签表示开始AOP的配置
3、使用aop:aspect标签表明配置切面
4、在aop:aspect标签内部使用对应标签来配置通知的类型
8.2.1 aop:config标签
复制代码
作用:表示开始Spring的AOP配置
8.2.2 aop:aspect标签
复制代码
作用:在aop:aspect标签内部使用对应标签来配置通知的类型

属性:
id:是给切面提供一个唯一标识
ref属性:是指定通知类bean的id

下面是关于通知类型的标签,出现在aop:aspect标签的内部

8.2.3 aop:before 前置通知标签
复制代码
作用:表示前置通知, 在切入点方法执行之前执行

method属性:用于指定切面类(Logger)中的哪个方法是前置通知

pointcut属性:用于指定切入点表达式,该表达式的含义的是对业务层的哪些方法进行增强

pointcut-ref属性:用于指定表达式配置的id

切入点表达式:

​ 关键字:execution(表达式)

​ 表达式的格式:
​ 修饰符名称 返回值名称 宝明名.方法名称(参数列表)

​ 标准表达式写法:

​ public void com.github.service.impl.AddressServiceImpl.saveAddress( )

​ 访问修饰符可以省略:

​ void com.github.service.impl.AddressServiceImpl.saveAddress( )

​ 返回值可以使用通配符" * "配置来表示任意返回值:

\* com.github.service.impl.AddressServiceImpl.saveAddress( )
​ 包名可以使用通配符" * "来配置,表示任意包,但是有几级包就要用几个*来表示

​ * *.*.*.*.AddressServiceImpl.saveAddress( )

 ​ 包名可以使用..表示当前包及其子包

 ​ ​ * *..AddressServiceImpl.saveAddress()

 ​ ​ 类名和方法名都可以使用*来实现通配

 ​ ​ * *..*.*( )

 ​ ​ 参数列表

 ​ ​ 可以直接写数据类型

 ​ ​ 基本类型直接写名称 如:int boolean

​ 引用数据类型写包的全限定类名 如:java.lang.String

复制代码
 ​ ​ 可以使用*来表示任意类型,但是必须有参数

 ​ ​ * *..*.*(* )

 ​ ​ 可以使用..表示有无参数都可以,有参数可以是任意类型

 ​ ​ 全通配符写法:

 ​ ​ * *..*.*(..)

 ​ ​ 但是在实际开发中,我们值对service进行aop管理,所以常写为:

 ​ ​ * com.github.service.impl.*.*(..)

如:
<bean id="addressService" class="com.github.service.impl.AddressServiceImpl"></bean>
<bean id="logger" class="com.github.utils.Logger"></bean>
<aop:config>
        <!--配置切入点-->
        <aop:aspect id="aop" ref="logger">
            <!--配置切面-->
            <aop:before method="printLog" pointcut=
                        "execution(* com.github.service.impl.*.*())"></aop:before>
        </aop:aspect>
    </aop:config>
8.2.4 aop:after-returning后置通知标签
复制代码
作用:表示后置通知,在切入点方法正常执行之后执行,后置通知和异常通知永远只能执行一个

method属性:用于指定切面类(Logger)中的哪个方法是前置通知

pointcut属性:用于指定切入点表达式,该表达式的含义的是对业务层的哪些方法进行增强

pointcut-ref属性:用于指定表达式配置的id
8.2.5 aop:after-throwing异常通知标签
复制代码
作用:表示异常通知,在切入方法执行产生异常后执行,异常通知和后置通知永远只能执行一个

method属性:用于指定切面类(Logger)中的哪个方法是前置通知

pointcut属性:用于指定切入点表达式,该表达式的含义的是对业务层的哪些方法进行增强

pointcut-ref属性:用于指定表达式配置的id
8.2.6 aop:after最终通知标签
复制代码
作用:表示最终通知,无论切入点是否正常执行都会在其后执行

method属性:用于指定切面类(Logger)中的哪个方法是前置通知

pointcut属性:用于指定切入点表达式,该表达式的含义的是对业务层的哪些方法进行增强

pointcut-ref属性:用于指定表达式配置的id
8.2.7 aop:pointcut配置表达式 标签
复制代码
作用:配置切入点表达式

id属性:用于指定表达式内部的唯一表达式的标识

expression属性:用于指定表达式的内容

注:此标签写在aop:aspect标签内部只能当前切面使用
它还可以写在aop:aspect标签外部,表示所有的切面都可以使用

8.3 Spring基于XMl配置的AOP案例

8.3.1 Address接口

地址接口类

复制代码
package com.github.service;
public interface IAddressService {
    /**
     * 模拟保存账户
     */
    void saveAddress();

    /**
     * 模拟更新账户
     * @param i
     */
    void updateAddress(int i);

    /**
     * 模拟删除账户
     * @return
     */
    int deleteAddress();
}
8.3.2 Address的实现类

地址接口实现类

复制代码
package com.github.service.impl;

import com.github.service.IAddressService;

/**
 * @param
 * @return
 */
public class AddressServiceImpl implements IAddressService {

    public void saveAddress() {
        System.out.println("保存了地址");
    }

    public void updateAddress(int i) {
        System.out.println("更新了用户"+i);
    }

    public int deleteAddress() {
        System.out.println("删除了用户");
        return 0;
    }
}
8.3.3 Looger工具类

工具模拟日志类

复制代码
package com.github.utils;

import org.aspectj.lang.ProceedingJoinPoint;
/**
 * 用于记录日志的工具类,里面提供了公共的代码
 */
public class Logger {

    /**
     * 用于打印日志:计划让其在切入点方法执行之前执行(切入点就是业务层方法)
     */
    public void beforePrintLog(){
        System.out.println("前置通知Logger类的beforePrintLog方法正在记录日志......");
    }

    /**
     * 用于打印日志:计划让其在切入点方法执行之前执行(切入点就是业务层方法)
     */
    public void afterReturningPrintLog() {
        System.out.println("后置通知Logger类的afterReturningPrintLog方法正在记录日志......");
    }

    /**
     * 用于打印日志:计划让其在切入点方法执行之前执行(切入点就是业务层方法)
     */
    public void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类的afterThrowingPrintLog方法正在记录日志......");
    }

    /**
     * 用于打印日志:计划让其在切入点方法执行之前执行(切入点就是业务层方法)
     */
    public void afterPrintLog(){
        System.out.println("最终通知Logger类的afterPrintLog方法正在记录日志......");
    }
    
    public Object aroundPrintLog(ProceedingJoinPoint pjp){
        Object retValue = null;
        try {
            Object[] args = pjp.getArgs();//获取切入方法执行所需的参数

            System.out.println("(前置通知)Logger类中的aroundPrintLog方法开始执行记录日志");

            retValue = pjp.proceed(args);//执行方法(明确调用业务层方法(切入点))

            System.out.println("(后置通知)Logger类中的aroundPrintLog方法开始执行记录日志");
            return retValue;

        }catch (Throwable t){
            System.out.println("(异常通知)Logger类中的aroundPrintLog方法开始执行记录日志");;
            throw new RuntimeException(t);
        }finally {
            System.out.println("(最终通知)Logger类中的aroundPrintLog方法开始执行记录日志");
        }


    }

}
8.3.4 bean.xml配置文件

引入头文件

复制代码
<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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置spring的ioc,把service对象配置进来-->
    <bean id="addressService" class="com.github.service.impl.AddressServiceImpl"></bean>
    <bean id="logger" class="com.github.utils.Logger"></bean>

    <!--配置AOP-->
    <aop:config>
        <!--配置切入点表达式
            id属性用于指定表达式内部的唯一表达式的标识
            expression属性:用于指定表达式的内容
            注:此标签写在<aop:aspect>标签内部只能当前切面使用
                它还可以写在<aop:aspect>变迁外部,表示所有的切面都可以使用
        -->
        <aop:pointcut id="pt1" expression="execution(* com.github.service.impl.*.*(..))"></aop:pointcut>
        <!--配置切面-->
        <aop:aspect id="aop" ref="logger">
            <!--配置前置通知:在切入点方法执行之前执行-->
            <aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>

            <!--配置后置通知:在切入点方法正常执行之后执行,他和异常通知永远只能执行一个-->
            <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>

            <!--配置异常通知:在切入点方法执行产生异常之后执行,他和后置通知永远只能执行一个-->
            <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>

            <!--配置最终通知:无论切入点方法是否正常执行它都会在其后执行-->
            <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
        </aop:aspect>
    </aop:config>

</beans>

运行结果

8.4 Spring中的环绕通知

通知的类型和代理对象的参照

8.4.1 aop:around 环绕通知标签

作用:表示环绕配置,它是Spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式

method 属性:用于指定切面类(Logger)中的哪个方法是前置通知

pointcut 属性:用于指定切入点表达式,该表达式的含义的是对业务层的哪些方法进行增强

pointcut-ref 属性:用于指定表达式配置的id

ProceedingJoinPoint 接口:该接口有一个方法proceed(),此方法就相当于明确调用切入点方法

复制代码
    <!--配置spring的ioc,把service对象配置进来-->
    <bean id="addressService" class="com.github.service.impl.AddressServiceImpl"></bean>
    <bean id="logger" class="com.github.utils.Logger"></bean>
    <!--配置AOP-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.github.service.impl.*.*(..))"></aop:pointcut>
        <!--配置切面-->
        <aop:aspect id="aop" ref="logger">
            <!--配置环绕切面  切面详情请参考Logger内部的aroundPrintLog方法-->
            <aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>
        </aop:aspect>
    </aop:config>

Looger的环绕方法

复制代码
/**
     * 环绕通知
     *
     *  问题:
     *      当我们使用aop配置了环绕通知后,切入点方法aroundPrintLog方法没有执行
     *  分析:
     *      当我们比较动态代理的代码的时候,发现使用动态代理时有明确的切入点方法value = method.invoke(Object,arg...[]);
     *      而我们代码中却没有
     */
//    public void aroundPrintLog(){
//        System.out.println("环绕通知Logger类的aroundPrintLog方法正在记录日志......");
//    }

    /**
     *  解决方法:
     *      Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法
     *      该接口可以作为环绕通知的方法参数,再执行程序时,Spring框架会为我们提供接口的实现类供我们使用
     *
     *  spring中的环绕通知
     *      它是Spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式
     *
     * @return
     */
    public Object aroundPrintLog(ProceedingJoinPoint pjp){
        Object retValue = null;
        try {
            Object[] args = pjp.getArgs();//获取切入方法执行所需的参数

            System.out.println("(环绕------前置通知)Logger类中的aroundPrintLog方法开始执行记录日志");

            retValue = pjp.proceed(args);//执行方法(明确调用业务层方法(切入点))

            System.out.println("(环绕------后置通知)Logger类中的aroundPrintLog方法开始执行记录日志");
            return retValue;

        }catch (Throwable t){
            System.out.println("(环绕------异常通知)Logger类中的aroundPrintLog方法开始执行记录日志");;
            throw new RuntimeException(t);
        }finally {
            System.out.println("(环绕------最终通知)Logger类中的aroundPrintLog方法开始执行记录日志");
        }
    }
}

执行结果

九、Spring基于注解的AOP

9.1 Spring的AOP常用注解

@Aspect( )

作用:表示当前类是一个切面类

@Pointcut( )

作用:配置切点通用表达式

复制代码
@Pointcut("execution(* com.github.service.impl.*.*(..))")
    public void pt1(){ 
    	
    }

@Before( )

作用:表示当前方法是一个前置通知方法

value属性:切入点表达式的引用

复制代码
 @Before(value = "pt1()")//前置通知
    public void beforePrintLog(){
        System.out.println("前置通知Logger类的beforePrintLog方法正在记录日志......");
    }

@AfterReturning( )

作用:表示当前方法是一个后置通知方法

value属性:切入点表达式的引用

复制代码
@AfterReturning("pt1()")//后置通知
    public void afterReturningPrintLog() {
        System.out.println("后置通知Logger类的afterReturningPrintLog方法正在记录日志......");
    }

@AfterThrowing( )

作用:表示当前方法是一个异常通知方法

value属性:切入点表达式的引用

复制代码
 @AfterThrowing("pt1()")//异常通知
    public void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类的afterThrowingPrintLog方法正在记录日志......");
    }

@After( )

作用:表示当前方法是一个最终通知方法

value属性:切入点表达式的引用

复制代码
 @After(value = "pt1()")//最终通知
    public void afterPrintLog(){
        System.out.println("最终通知Logger类的afterPrintLog方法正在记录日志......");
    }

@Around( )

作用:表示当前方法是一个环绕通知方法

value属性:切入点表达式的引用

复制代码
@Around("pt1()")//环绕通知
    public void aroundPrintLog(){
        System.out.println("环绕通知Logger类的aroundPrintLog方法正在记录日志......");
    }  

@EnableAspectJAutoProxy

作用:表示spring开启了aop,配置在切面类

9.2 基于注解AOP的简单演示

9.2.1 加载service到IOC容器
复制代码
@Service("addressService")
public class AddressServiceImpl implements IAddressService {

    public void saveAddress() {
        System.out.println("保存了地址");
    }

    public void updateAddress(int i) {
        System.out.println("更新了用户"+i);
    }

    public int deleteAddress() {
        System.out.println("删除了用户");
        return 0;
    }
}
9.2.2 加载Logger对象进Spring的IOC容器
复制代码
/**
 * 用于记录日志的工具类,里面提供了公共的代码
 * @param
 * @return
 */
@Component("logger")//加载入springIOC容器
@Aspect//表示当前类是一个切面类
public class Logger {

    //配置切入点表达式
    @Pointcut("execution(* com.github.service.impl.*.*(..))")
    public void pt1(){ }

    @Before("pt1()")//前置通知
    public void beforePrintLog(){
        System.out.println("前置通知Logger类的beforePrintLog方法正在记录日志......");
    }

    @AfterReturning("pt1()")//后置通知
    public void afterReturningPrintLog() {
        System.out.println("后置通知Logger类的afterReturningPrintLog方法正在记录日志......");
    }

    @AfterThrowing("pt1()")//异常通知
    public void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类的afterThrowingPrintLog方法正在记录日志......");
    }

    @After("pt1()")//最终通知
    public void afterPrintLog(){
        System.out.println("最终通知Logger类的afterPrintLog方法正在记录日志......");
    }

    @Around("pt1()")//环绕通知
    public void aroundPrintLog(){
        System.out.println("环绕通知Logger类的aroundPrintLog方法正在记录日志......");
    }
}
9.2.3 bean.xml配置文件
复制代码
 <!--配置Spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.github"></context:component-scan>
    <!--配置Spring开启注解aop的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
9.2.4 使用纯注解的方式

添加配置类

复制代码
package com.github.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * 这里是Aop的配置类
 * @param
 * @return
 */
@Configuration//标识为配置类
@ComponentScan("com.github")//标识需要扫描的包
@EnableAspectJAutoProxy//标识spring开启Aop
public class AopConfig {

}

十、JdbcTemplate

10.1 概念

它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很多的操作模板类。

操作关系型数据的:

JdbcTemplate

HibernateTemplate

操作 nosql 数据库的:

​ RedisTemplate

操作消息队列的:

​ JmsTemplate

我们今天的主角在 spring-jdbc-5.0.2.RELEASE.jar 中,我们在导包的时候,除了要导入这个 jar 包

外,还需要导入一个 spring-tx-5.0.2.RELEASE.jar(它是和事务相关的)。

10.2 jdbcTemplate的创建

复制代码
JdbcTemplate template = new JdbcTemplate(DBUtls.getDataSource());

10.2 查询多个

复制代码
 List<Account> accounts = template.query("select * from account where name = ?", new 
 BeanPropertyRowMapper<Account>(Account.class), name);

10.3 查询单个

复制代码
 List<Account> accounts =  template.query("select * from account where id = ?" ,new 
 BeanPropertyRowMapper<Account>(Account.class),id);

10.4 增删改

复制代码
template.update("update account set name = ?, money = ? where     
id=?",account.getName(),account.getMoney(),account.getId());

10.5 查询单行单列(查询记录条数)

复制代码
template.query("select count(*) from account",Integer.class);

10.6 在dao中使用JdbcTemplate

10.6.1 准备实体类
复制代码
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id; }
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name; }
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money; }
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
10.6.2 第一种方式:在dao中定义 JdbcTemplate

账户接口类

复制代码
/**
* 账户的接口
*/
public interface IAccountDao {
    /**
    * 根据 id 查询账户信息
    * @param id
    * @return
    */
    Account findAccountById(Integer id);
    /**
    * 根据名称查询账户信息
    * @return
    */
    Account findAccountByName(String name);
    /**
    * 更新账户信息
    * @param account
    */
    void updateAccount(Account account);
}

接口实现类

复制代码
public class AccountDaoImpl implements IAccountDao {
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
    
	@Override
	public Account findAccountById(Integer id) {
		List<Account> list = jdbcTemplate.query("select * from account where id = ? 
		",new AccountRowMapper(),id);
		return list.isEmpty()?null:list.get(0);
	}
                                                
	@Override
	public Account findAccountByName(String name) {
		List<Account> list = jdbcTemplate.query("select * from account where name 
		= ? ",new AccountRowMapper(),name);
		if(list.isEmpty()){
			return null; 
        }
		if(list.size()>1){
			throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
		}
		return list.get(0);
	}
	@Override
	public void updateAccount(Account account) {
		jdbcTemplate.update("update account set money = ? where id = ? 
		",account.getMoney(),account.getId());
	} 
}

bean.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 
 http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- 配置一个 dao -->
    <bean id="accountDao" class="com.github.dao.impl.AccountDaoImpl">
		<!-- 注入 jdbcTemplate --> 
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>
		<!-- 配置一个数据库的操作模板:JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property 			name="dataSource" ref="dataSource"></property>
	</bean>
    <!-- 配置数据源 -->
    <bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 		<property name="driverClassName"value="com.mysql.jdbc.Driver"></property>
      <property name="url" value="jdbc:mysql:///spring_day04"></property> <property name="username" value="root"></property> <property name="password" value="1234">
        </property>
	</bean>
</beans>

有个小问题。就是我们的 dao 有很多时,每个 dao 都有一些重复性的代码。下面就是重复代码:

复制代码
private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

​ this.jdbcTemplate = jdbcTemplate;

}
4.6.3 第二种方式:让dao 继承JdbcDaoSupport

JdbcDaoSupport 是 spring 框架为我们提供的一个类,该类中定义了一个 JdbcTemplate 对象,我们可以

直接获取使用,但是要想创建该对象,需要为其提供一个数据源:具体源码如下:

复制代码
public abstract class JdbcDaoSupport extends DaoSupport {
	//定义对象
	private JdbcTemplate jdbcTemplate;
	//set 方法注入数据源,判断是否注入了,注入了就创建 JdbcTemplate
	public final void setDataSource(DataSource dataSource) {
		if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) { 
            //如果提供了数据源就创建 JdbcTemplate
			this.jdbcTemplate = createJdbcTemplate(dataSource);
			initTemplateConfig();
		}
    }
    
	//使用数据源创建 JdcbTemplate
	protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}
	//当然,我们也可以通过注入 JdbcTemplate 对象
	public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
   		this.jdbcTemplate = jdbcTemplate;
		initTemplateConfig();
	}
    
	//使用 getJdbcTmeplate 方法获取操作模板对象
	public final JdbcTemplate getJdbcTemplate() {
 		return this.jdbcTemplate;
    }

账户的接口

复制代码
public interface IAccountDao {
    /**
    * 根据 id 查询账户信息
    * @param id
    * @return
    */
    Account findAccountById(Integer id);
    /**
    * 根据名称查询账户信息
    * @return
    */
    Account findAccountByName(String name);
    /**
    * 更新账户信息
    * @param account
    */
    void updateAccount(Account account);
}

账户的持久层实现类 (此版本 dao,只需要给它的父类注入一个数据源)

复制代码
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
    @Override
    public Account findAccountById(Integer id) {
        //getJdbcTemplate()方法是从父类上继承下来的。
        List<Account> list = getJdbcTemplate().query("select * from account where 
        id = ? ",new AccountRowMapper(),id);
        return list.isEmpty()?null:list.get(0);
    }
                                                     
	@Override
	public Account findAccountByName(String name) {
    //getJdbcTemplate()方法是从父类上继承下来的。
    List<Account> list = getJdbcTemplate().query("select * from account where 
    name = ? ",new AccountRowMapper(),name);
    if(list.isEmpty()){
        return null; 
    }
	if(list.size()>1){
		throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
	}
	return list.get(0);
	}
                                                 
	@Override
	public void updateAccount(Account account) {
		//getJdbcTemplate()方法是从父类上继承下来的。
		getJdbcTemplate().update("update account set money = ? where id = ? 			",account.getMoney(),account.getId());
	}
}

bean.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 
 http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- 配置 dao2 -->
    <bean id="accountDao2" class="com.github.dao.impl.AccountDaoImpl2">
	<!-- 注入 dataSource -->
        <property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 配置数据源 --> 
    <bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 
        <property name="url" value="jdbc:mysql:///spring_day04"></property> 
        <property name="username" value="root"></property> 
        <property name="password" value="1234"></property>
	</bean>
</beans>

两种实现的区别:

​ 第一种在dao类中定义JdbcTemplate的方式,适用于所有的配置方式(xml配置方式和注解配置的方式)

​ 第二种让dao继承JdbcDaoSupport的方式,只能基于xml配置的方式,基于注解的方式不能使用

十一、Spring中的事务控制

11.1 Spring事务控制需要明确的

第一:JavaEE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解决方案。

第二:spring 框架为我们提供了一组事务控制的接口。具体在后面的第二小节介绍。这组接口是在

spring-tx-5.0.2.RELEASE.jar 中。

第三:spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。我们学习的重点是使用配置的方式实现。

11.2 Spring中事务控制的API的介绍

11.2.1 PlatformTransactionManager

此接口是spring中的事务管理器,它提供了我们常用的操作事务的方法

//获取事务状态

TransactionStatus getTransaction(TransactionDefinition definition)

//提交事务

void commit(TransactionStatus status)

//回滚事务

void rollback(TransactionStatus status)

在我们开发中都是使用它的实现类

复制代码
真正管理事务的对象
	org.springframework.jdbc.datasource.DataSourceTransactionManager 使用 SpringJDBC 或 iBatis 进行持久化数据时使用
	org.springframework.orm.hibernate5.HibernateTransactionManager 使用Hibernate 版本进行持久化数据时使用
11.2.2 TrnasactionDefinition

该接口是事务的定义信息对象,里面有如下方法

复制代码
//获取事务对象名称

String getName( );

//获取事务隔离级别

int getIsolationLeve( )

//获取事务传播行为

int getPropagationBehavior( )

//获取事务超时时间

int getTimeout

//获取事务是否只读

//读写型事务:增加、删除、修改事务开启

//只读型事务:执行查询是时,也会开启事务

boolean isReadOnly( )
11.2.2.1 事务的隔离级别
11.2.2.2 事务的传播行为
复制代码
REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务,加入到这个事务。是默认值

SUPPORTS:支持当前事务,如果当前没有事务,就以非事务的方式执行(没有事务)

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

REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起

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

NEVER:以非事务方式运行,如果当前存在事务,抛出异常

NESTED:如果当前存在事务,则在嵌套事务内执行,如果当前没有事务,则执行REQUIRED 类似的操作。
11.2.2.3 超时时间
复制代码
默认值为-1,表示没有超时限制。如果有,以秒为单位。
11.2.2.4 是否是只读事务
复制代码
建议查询是设为只读型事务
11.2.3 TransactionStatus
复制代码
此接口是事务具体的运行状态

TranactionStatus接口描述了某个时间点上事务对象的状态信息,包含6个具体的操作

//刷新事务

void flush( )

//获取是否存在存储点

boolean hasSavepoint( )

//获取事务是否完成

boolean isCompleted( )

//获取事务是否为新的事务

boolean isNewTransaction( )

//获取事务是否回滚

boolean isRollbackObly( )

//设置事务回滚

void setRollbackOnly( )

11.3 Spring中基于XML的声明式事务控制

11.3.0 配置步骤

步骤一:配置事务管理器DataSourceTransactionManager

复制代码
<!--配置事务管理器-->
<bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dateSource"></property>
</bean>

步骤二:配置事务通知

​ 需要导入事务的约束到bean.xml的约束中,tx的名称空间和约束,同时也需要aop

​ 使用tx:advice标签配置事务通知

​ id属性:给事务通知起一个唯一标识

​ transaction-manager:给事务提供一个事务管理器引用

复制代码
<!--配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--
            配置事务的属性:
				name:指定业务层的核心方法名称
                isolation:"指定事务的隔离级别,默认值是DEFAULT,表示使用数据库的默认隔离级别"
                propagation:"用于指定事务的传播行为。默认值为REQUIRED,表示一定会有事务,增删改的选择,查询的方法可以选择SUPPORTS".
                read-only:"用于指定事务是否只读,只有查询方法才能设置为true,默认值为false,表示读写"
                timeout:"用于表示事务的超时时间,默认值为-1,表示永不超时,如果指定了时间,以秒为单位"
                rollback-for:"用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,表示任何异常都回滚。"
                no-rollback-for:"用于指定一个异常,当产生该异常时,事务不回滚,当产生其他异常时事务回滚,没有默认值,表示任何异常都回滚"
        -->
        <tx:attributes>
            <!-- REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务,加入到这个事务。默认值
			     SUPPORTS:支持当前事务,如果当前没有事务,就以非事务的方式执行(没有事务)
			-->
            <tx:method name="transfer" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

步骤三:建立AOP中的通用切入点表达式

步骤四:建立事务通知和切入点表达式的对应关系

复制代码
<!--配置AOP-->
    <aop:config >
        <!--配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.github.service.impl.*.*(..))"></aop:pointcut>
        <!--建立切入点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

步骤五:配置事务的属性,在事务的通知tx:advice标签的内部配置

11.3.1 导入依赖
复制代码
<dependencies>
        <!--spring的IOC容器-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--spring的jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--spring支持事务的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--mysql数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <!--aop切点表达式的依赖-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>

        <!--junit测试类-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--spring整合junit测试的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
11.3.2 account持久层接口
复制代码
package com.github.dao;

import com.github.domain.Account;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);

    /**
     * 根据用户名查询账户
     * @param name
     * @return
     */
    Account findAccountByName(String name);

    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
}
11.3.3 account持久层实现类
复制代码
package com.github.dao.impl;

import com.github.dao.IAccountDao;
import com.github.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

/**账户的持久层实现类
 * @param
 * @return
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

    @Override
    public Account findAccountById(Integer id) {
        List<Account> accounts =  getJdbcTemplate().query("select * from account where id = ?" ,new BeanPropertyRowMapper<Account>(Account.class),id);
        return accounts.isEmpty() ? null : accounts.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts.isEmpty()){
            return null;
        }
        if (accounts.size() > 1){
            throw new RuntimeException("结果集不唯一");
        }

        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        getJdbcTemplate().update("update account set name = ?, money = ? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}
11.3.4 account业务层接口
复制代码
package com.github.service;

import com.github.domain.Account;

/**
 * 业务层的接口类
 * @param
 * @return
 */
public interface IAccountService {

    /**
     * 根据用户id查询用户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);

    /**
     * 转账
     * @param sourceName  转出账户名称
     * @param targetName  转入账户名称
     * @param money       转账金额
     */
    void transfer(String sourceName,String targetName,Float money);

}
11.3.5 account业务层实现类
复制代码
package com.github.service.impl;

import com.github.dao.IAccountDao;
import com.github.domain.Account;
import com.github.service.IAccountService;

import java.util.List;

/**
 * @param
 * @return
 */
public class AccountServiceImpl implements IAccountService {
    private IAccountDao dao;

    public void setDao(IAccountDao dao) {
        this.dao = dao;
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return dao.findAccountById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer...");
        //1、根据名称查询转出账户
        Account source = dao.findAccountByName(sourceName);
        //2、根据名称查询转入账户
        Account target = dao.findAccountByName(targetName);
        //3、转出账户减钱
        source.setMoney(source.getMoney() - money);
        //4、转入账户加钱
        target.setMoney(target.getMoney() + money);
        //5、更新转出账户
        dao.updateAccount(source);
        //模拟异常
//        int i = 1 / 0;
        //6、更新转入账户
        dao.updateAccount(target);

    }
}
11.3.6 bean.xml配置文件
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.github.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dateSource"></property>
    </bean>
    
    <!--配置业务层-->
    <bean id="accountService" class="com.github.service.impl.AccountServiceImpl">
        <property name="dao" ref="accountDao"></property>
    </bean>

    <!--配置数据源文件dataSource-->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/eesy_spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123"></property>
    </bean>
    <!--
        spring中基于XML声明式事务控制配置步骤
        1、配置事务管理器
        2、配置事务通知
            需要导入事务的约束到bean.xml的约束中 tx的名称空间和约束,同时也需要aop的
            使用<tx:advice>标签配置事务通知
                属性:id:给事务通知起一个唯一的标志
                      transaction-manager:给事务通知提供一个事务管理器引用
        3、配置AOP中的通用切入点表达式
        4、建立事务通知和切入点表达式的对应关系
        5、配置事务的属性
            在事务的通知<tx:advice>标签的内部配置
    -->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

    <!--配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--
            配置事务的属性:
                isolation:"指定事务的隔离级别,默认值是DEFAULT,表示使用数据库的默认隔离级别"
                propagation:"用于指定事务的传播行为。默认值为REQUIRED,表示一定会有事务,增删改的选择,查询的方法可以选择SUPPORTS".
                read-only:"用于指定事务是否只读,只有查询方法才能设置为true,默认值为false,表示读写"
                timeout:"用于表示事务的超时时间,默认值为-1,表示永不超时,如果指定了时间,以秒为单位"
                rollback-for:"用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,表示任何异常都回滚。"
                no-rollback-for:"用于指定一个异常,当产生该异常时,事务不回滚,当产生其他异常时事务回滚,没有默认值,表示任何异常都回滚"
        -->
        <tx:attributes>
            <tx:method name="transfer" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--配置AOP-->
    <aop:config >
        <!--配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.github.service.impl.*.*(..))"></aop:pointcut>
        <!--建立切入点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
</beans>

11.4 Sring中基于注解的声明式事务控制

@Transactiona

复制代码
当标于类前时, 标示类中所有方法都进行事务处理

propagation属性:事务传播行为,默认值为REQUIRED

redaOnly属性:用于指定事务是否只读,只有查询方法一般设置为true,默认为false,表示读写

当出现在方法上时,表示配置这一个方法的事务属性

@EnableTransactionManagement

表示开启事务管理,用于使用纯注解配置事务管理器的注释

bean.xml配置文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd>
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">


    <!--配置Spring创建容器要扫描的包-->
    <context:component-scan base-package="com.github"></context:component-scan>

    <!--配置jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

    <!--配置数据源文件dataSource-->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/eesy_spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123"></property>
    </bean>
    <!--
        spring中基于注解的声明式事务控制配置步骤
        1、配置事务管理器
        2、开启Spring对注解事务的支持
        3、在需要事务支持的地方使用@Transactional注解

    -->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

    <!--开启Spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

持久层实现类

复制代码
package com.github.dao.impl;

import com.github.dao.IAccountDao;
import com.github.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;

/**账户的持久层实现类
 * @param
 * @return
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Account findAccountById(Integer id) {
        List<Account> accounts =  jdbcTemplate.query("select * from account where id = ?" ,new BeanPropertyRowMapper<Account>(Account.class),id);
        return accounts.isEmpty() ? null : accounts.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts.isEmpty()){
            return null;
        }
        if (accounts.size() > 1){
            throw new RuntimeException("结果集不唯一");
        }

        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set name = ?, money = ? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}

业务层实现类

复制代码
package com.github.service.impl;

import com.github.dao.IAccountDao;
import com.github.domain.Account;
import com.github.service.IAccountService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @param
 * @return
 */
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读型事务的配置
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao dao;

    @Override
    public Account findAccountById(Integer accountId) {
        return dao.findAccountById(accountId);
    }

    //配置此方法的事务传播行为为REQUIRED读写类型
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer...");
        //1、根据名称查询转出账户
        Account source = dao.findAccountByName(sourceName);
        //2、根据名称查询转入账户
        Account target = dao.findAccountByName(targetName);
        //3、转出账户减钱
        source.setMoney(source.getMoney() - money);
        //4、转入账户加钱
        target.setMoney(target.getMoney() + money);
        //5、更新转出账户
        dao.updateAccount(source);
        //模拟异常
        int i = 1 / 0;
        //6、更新转入账户
        dao.updateAccount(target);

    }
}

十二、Spring的新特性

12.1 与JDK相关的升级

12.1.1 jdk版本要求
复制代码
spring5.0 在 2017 年 9 月发布了它的 GA(通用)版本。该版本是基于 jdk8 编写的,所以 jdk8 以下版本

将无法使用。同时,可以兼容 jdk9 版本。

tomcat 版本要求 8.5 及以上。

注:

我们使用 jdk8 构建工程,可以降版编译。但是不能使用 jdk8 以下版本构建工程。

由于 jdk 和 tomcat 版本的更新,我们的 IDE 也需要同时更新。(目前使用的 eclipse 4.7.2)

利用jdk8版本更新的内容

复制代码
第一:在jdk1.8后,spring对创建对象的效率上做了增强

第二:@NonNull 注解和@Nullable 注解的使用

用 @Nullable 和 @NotNull 注解来显示表明可为空的参数和以及返回值。这样就够在编译的时候处

理空值而不是在运行时抛出 NullPointerExceptions。

第三:日志记录方面

Spring Framework 5.0 带来了 Commons Logging 桥接模块的封装, 它被叫做 spring-jcl 而

不是标准的 Commons Logging。当然,无需任何额外的桥接,新版本也会对 Log4j 2.x, SLF4J, JUL

( java.util.logging) 进行自动检测。
12.1.2 核心容器的更新
复制代码
Spring Framework 5.0 现在支持候选组件索引作为类路径扫描的替代方案。该功能已经在类路径扫描器中

添加,以简化添加候选组件标识的步骤。

应用程序构建任务可以定义当前项目自己的 META-INF/spring.components 文件。在编译时,源模型是

自包含的,JPA 实体和 Spring 组件是已被标记的。

从索引读取实体而不是扫描类路径对于小于 200 个类的小型项目是没有明显差异。但对大型项目影响较大。

加载组件索引开销更低。因此,随着类数的增加,索引读取的启动时间将保持不变。

加载组件索引的耗费是廉价的。因此当类的数量不断增长,加上构建索引的启动时间仍然可以维持一个常数,

不过对于组件扫描而言,启动时间则会有明显的增长。

这个对于我们处于大型 Spring 项目的开发者所意味着的,是应用程序的启动时间将被大大缩减。虽然 20

或者 30 秒钟看似没什么,但如果每天要这样登上好几百次,加起来就够你受的了。使用了组件索引的话,就能帮

助你每天过的更加高效。

你可以在 Spring 的 Jira 上了解更多关于组件索引的相关信息。
12.1.3 JetBrains Kotlin语言支持

Kolin概述:是一种支持函数式编程编程风格的面向对象语言。Kotlin 运行在 JVM 之上,但运行环境并不限于 JVM。

Kolin 的示例代码:

{

("/movie" and accept(TEXT_HTML)).nest {

GET("/", movieHandler::findAllView)

GET("/{card}", movieHandler::findOneView)

}

("/api/movie" and accept(APPLICATION_JSON)).nest {

GET("/", movieApiHandler::findAll)

GET("/{id}", movieApiHandler::findOne)

}

}

Kolin 注册 bean 对象到 spring 容器:

val context = GenericApplicationContext {

registerBean()

registerBean { Cinema(it.getBean()) }

12.1.4 响应式编程风格
复制代码
此次 Spring 发行版本的一个激动人心的特性就是新的响应式堆栈 WEB 框架。这个堆栈完全的响应式且非

阻塞,适合于事件循环风格的处理,可以进行少量线程的扩展。

Reactive Streams 是来自于 Netflix, Pivotal, Typesafe, Red Hat, Oracle, Twitter 以及

Spray.io 的工程师特地开发的一个 API。它为响应式编程实现的实现提供一个公共的 API,好实现

Hibernate 的 JPA。这里 JPA 就是这个 API, 而 Hibernate 就是实现。

Reactive Streams API 是 Java 9 的官方版本的一部分。在 Java 8 中, 你会需要专门引入依赖来使

用 Reactive Streams API。

Spring Framework 5.0 对于流式处理的支持依赖于 Project Reactor 来构建, 其专门实现了

Reactive Streams API。

Spring Framework 5.0 拥有一个新的 spring-webflux 模块,支持响应式 HTTP 和 WebSocket 客

户端。Spring Framework 5.0 还提供了对于运行于服务器之上,包含了 REST, HTML, 以及 WebSocket 风

格交互的响应式网页应用程序的支持。

在 spring-webflux 中包含了两种独立的服务端编程模型:

基于注解:使用到了@Controller 以及 Spring MVC 的其它一些注解;

使用 Java 8 lambda 表达式的函数式风格的路由和处理。

有 了 Spring Webflux, 你现在可以创建出 WebClient, 它是响应式且非阻塞的,可以作为

RestTemplate 的一个替代方案。

这里有一个使用 Spring 5.0 的 REST 端点的 WebClient 实现:

WebClient webClient = WebClient.create();

Mono person = webClient.get()

.uri("http://localhost:8080/movie/42")

.accept(MediaType.APPLICATION_JSON)

.exchange()

.then(response -> response.bodyToMono(Movie.class));
12.1.5Junit5 支持
复制代码
完全支持 JUnit 5 Jupiter,所以可以使用 JUnit 5 来编写测试以及扩展。此外还提供了一个编程以及

扩展模型,Jupiter 子项目提供了一个测试引擎来在 Spring 上运行基于 Jupiter 的测试。

另外,Spring Framework 5 还提供了在 Spring TestContext Framework 中进行并行测试的扩展。

针对响应式编程模型, spring-test 现在还引入了支持 Spring WebFlux 的 WebTestClient 集成测

试的支持,类似于 MockMvc,并不需要一个运行着的服务端。使用一个模拟的请求或者响应, WebTestClient

就可以直接绑定到 WebFlux 服务端设施。

你可以在这里找到这个激动人心的 TestContext 框架所带来的增强功能的完整列表。
12.1.6 依赖的类库更新
复制代码
终止的类库

Portlet.
Velocity.
JasperReports.
XMLBeans.
JDO.
Guava.

支持的类库

Jackson 2.6+
EhCache 2.10+ / 3.0 GA
Hibernate 5.0+
JDBC 4.0+
XmlUnit 2.x+
OkHttp 3.x+
Netty 4.1+
相关推荐
一只叫煤球的猫19 分钟前
写代码很6,面试秒变菜鸟?不卖课,面试官视角走心探讨
前端·后端·面试
bobz96544 分钟前
tcp/ip 中的多路复用
后端
bobz9651 小时前
tls ingress 简单记录
后端
皮皮林5512 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
你的人类朋友2 小时前
什么是OpenSSL
后端·安全·程序员
bobz9652 小时前
mcp 直接操作浏览器
后端
前端小张同学5 小时前
服务器部署 gitlab 占用空间太大怎么办,优化思路。
后端
databook5 小时前
Manim实现闪光轨迹特效
后端·python·动效
武子康6 小时前
大数据-98 Spark 从 DStream 到 Structured Streaming:Spark 实时计算的演进
大数据·后端·spark
该用户已不存在6 小时前
6个值得收藏的.NET ORM 框架
前端·后端·.net