zoukankan      html  css  js  c++  java
  • Spring入门笔记

    第1章 Spring概述

    1.1 spring概述

    1.1.1 spring是什么

    Spring是分层的 Java SE/EE应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control:反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层 Spring MVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的Java EE 企业应用开源框架。

    1.1.2 spring的优势

    • 方便解耦,简化开发

      通过 Spring 提供的 IoC 容器,可以将对象间的依赖关系交由 Spring进行控制,避免硬编码所造成的过度程序耦合。用户也不必再为单例模式类、属性文件解析等这些很底层的需求编写代码,可以更专注于上层的应用。

    • AOP编程的支持

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

    • 声明式事务的支持

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

    • 方便程序的测试

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

    • 方便集成各种优秀框架

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

    • 降低 JavaEE API的使用难度

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

    • Java源码是经典学习范例

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

    1.1.3 spring的体系结构

    第二章 Ioc的概念和作用

    2.1 程序的耦合和解耦

    耦合和解耦的概念在上学期的软件工程课中也学过,这里对其复习一下。

    2.1.1 什么是程序的耦合

    耦合性(Coupling),也叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调用模块的方式以及通过界面传送数据的多少。模块间的耦合度是指模块之间的依赖关系,包括控制关系、调用关系、数据传递关系。模块间联系越多,其耦合性越强,同时表明其独立性越差( 降低耦合性,可以提高其独立性)。耦合性存在于各个领域,而非软件设计中独有的,但是我们只讨论软件工程中的耦合。

    在软件工程中,耦合指的就是就是对象之间的依赖性。对象之间的耦合越高,维护成本越高。因此对象的设计应使类和构件之间的耦合最小。软件设计中通常用耦合度和内聚度作为衡量模块独立程度的标准。划分模块的一个准则就是高内聚低耦合。

    它有如下分类:

    (1) 内容耦合。当一个模块直接修改或操作另一个模块的数据时,或一个模块不通过正常入口而转入另一个模块时,这样的耦合被称为内容耦合。内容耦合是最高程度的耦合,应该避免使用之。

    (2) 公共耦合。两个或两个以上的模块共同引用一个全局数据项,这种耦合被称为公共耦合。在具有大量公共耦合的结构中,确定究竟是哪个模块给全局变量赋了一个特定的值是十分困难的。

    (3) 外部耦合 。一组模块都访问同一全局简单变量而不是同一全局数据结构,而且不是通过参数表传递该全局变量的信息,则称之为外部耦合。

    (4) 控制耦合 。一个模块通过接口向另一个模块传递一个控制信号,接受信号的模块根据信号值而进行适当的动作,这种耦合被称为控制耦合。

    (5) 标记耦合 。若一个模块 A 通过接口向两个模块 B 和 C 传递一个公共参数,那么称模块 B 和 C 之间存在一个标记耦合。

    (6) 数据耦合。模块之间通过参数来传递数据,那么被称为数据耦合。数据耦合是最低的一种耦合形式,系统中一般都存在这种类型的耦合,因为为了完成一些有意义的功能,往往需要将某些模块的输出数据作为另一些模块的输入数据。

    (7) 非直接耦合 。两个模块之间没有直接关系,它们之间的联系完全是通过主模块的控制和调用来实现的。

    总结:

    耦合是影响软件复杂程度和设计质量的一个重要因素,在设计上我们应采用以下原则:如果模块间必须存在耦合,就尽量使用数据耦合,少用控制耦合,限制公共耦合的范围,尽量避免使用内容耦合。

    内聚和耦合

    内聚标志一个模块内各个元素彼此结合的紧密程度,它是信息隐蔽和局部化概念的自然扩展。内聚是从功能角度来度量模块内的联系,一个好的内聚模块应当恰好做一件事。它描述的是模块内的功能联系。耦合是软件结构中各模块之间相互连接的一种度量,耦合强弱取决于模块间接口的复杂程度、进入或访问一个模块的点以及通过接口的数据。 程序讲究的是低耦合,高内聚。就是同一个模块内的各个元素之间要高度紧密,但是各个模块之间的相互依存度却要不那么紧密。

    内聚和耦合是密切相关的,同其他模块存在高耦合的模块意味着低内聚,而高内聚的模块意味着该模块同其他模块之间是低耦合。在进行软件设计时,应力争做到高内聚,低耦合

    我们在开发中,有些依赖关系是必须的,有些依赖关系可以通过优化代码来解除的。

    请看下面的示例代码:

    复制代码
    //账户的业务层实现类
    public class AccountServiceImpl implements AccountService {
    	private AccountDao accountDao = new AccountDaoImpl();
    }
    

    上面的代码表示:

    业务层调用持久层,并且此时业务层在依赖持久层的接口和实现类。如果此时没有持久层实现类,编译将不能通过。这种编译期依赖关系,应该在我们开发中杜绝。我们需要优化代码解决。

    再比如使用 JDBC 注册驱动时,我们为什么不使用 DriverManager 的 register 方法,而是采用 Class.forName 的方式?

    复制代码
    public class JdbcDemo {
    	public static void main(String[] args) throws Exception{
    		//1.注册驱动 
    		//DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 			
    		Class.forName("com.mysql.jdbc.Driver");
    		//2.获取连接 
    		//3.获取预处理 sql 语句对象 
    		//4.获取结果集 
    		//5.遍历结果集 
    	}
    } 
    

    原因就是:

    我们的类依赖了数据库的具体驱动类(MySQL),如果这时候更换了数据库品牌(比如 Oracle),需要修改源码来重新数据库驱动。这显然不是我们想要的。

    2.1.2 解决程序耦合的思路

    我们使用Jdbc时,是通过反射来注册驱动的,代码如下:

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

    此时的好处是,我们的类中不再依赖具体的驱动类,此时就算删除 mysql 的驱动 jar 包,依然可以编译(运行就不要想了,没有驱动不可能运行成功的)。

    同时,也产生了一个新的问题,mysql 驱动的全限定类名字符串是在 java 类中写死的,一旦要改还是要修改源码。

    解决这个问题也很简单,使用配置文件配置。

    2.1.3 工厂模式解耦

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

    那么,这个读取配置文件,创建和获取三层对象的类就是工厂。

    2.1.4 控制反转-Inversion Of Control

    工厂模式解耦的思路有2个问题:

    1、存哪去?

    分析:由于于我们是很多对象,肯定要找个集合来存。这时候有 Map 和 List 供选择。
    到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。

    所以我们的答案就是
    在应用加载时,创建一个 Map,用于存放三层对象。
    我们把这个 map 称之为容器

    2、什么是工厂?

    工厂就是负责给我们从容器中获取指定对象的类。这时候我们获取对象的方式发生了改变。

    原来:

    我们在获取对象时,都是采用 new 的方式。是主动的

    现在:

    我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的

    这种被动接收的方式获取对象的思想就是控制反转,它是 spring 框架的核心之一。

    第3章 使用 spring的 IOC解决程序耦合

    3.1 案例的前期准备 [会用]

    本章我们使用的案例是,账户的业务层和持久层的依赖关系解决。在开始 spring 的配置之前,我们要先准备一下环境。由于我们是使用 spring 解决依赖关系,并不是真正的要做增删改查操作,所以此时我们没必要写实体类。并且我们在此处使用的是 java 工程,不是 java web 工程。

    1.在pom.xml中添加 spring-context 的依赖

    2.创建业务层接口和实现类

    复制代码
    public interface AccountService {
    	void saveAccount();
    }
    
    public class AccoutServiceImpl implements AccountService {
    	private AccountDao accountDao = new AccountDaoImpl();//此处的依赖关系有待解决
    	
    	@Override
    	public void saveAccount(){
    		accountDao.saveAccount();
    	}
    }
    

    3.创建持久层接口和实现类

    public interface AccountDao {
    void saveAccount();
    }

    public class AccountDaoImpl implements AccountDao {
    @Override
    public void saveAccount() {
    System.out.println("保存了账户");
    }
    }

    3.2 基于 XML 的配置(入门案例)[掌握]

    1.在Maven工程的resource下创建bean.xml

    给配置文件导入约束:

    复制代码
    <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">
    	<!-- more bean definitions go here -->
    </beans>
    

    2.让spring管理资源,在配置文件中配置 service 和 dao

    复制代码
    <!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中 
    		id 属性:对象的唯一标识。 
    		class 属性:指定要创建对象的全限定类名 
    -->
    <!-- 配置 service -->    
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean> 
    <!-- 配置 dao -->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
    

    测试配置是否成功

    复制代码
    //模拟一个表现层
    public class Client {
    	public static void main(String[] args) {
    		//1.使用ApplicationContext接口,就是在获取spring容器
    		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    		//2.根据bean的id获取对象
    		AccountService as = (AccountService) ac.getBean("accountService");
    		System.out.println(as);
    		AccountDao ad = (AccountDao) ac.getBean("accountDao");
    		System.out.println(ad);
    	}
    }
    

    运行结果正常输出

    3.3 Spring基于 XML 的 IOC 细节[掌握]

    3.3.1 spring 中 工厂的类结构图

    3.3.1.1 BeanFactory和 ApplicationContext 的区别

    BeanFactory 才是 Spring 容器中的顶层接口。

    ApplicationContext 是它的子接口。

    BeanFactory 和 ApplicationContext 的区别:

    • 创建对象的时间点不一样。
      • ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。
      • BeanFactory:什么使用什么时候创建对象。

    3.3.1.2 ApplicationContext 接口的实现类

    • ClassPathXmlApplicationContext:
      它是从类的根路径下加载配置文件 推荐使用这种

    • FileSystemXmlApplicationContext:
      它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。

    • AnnotationConfigApplicationContext:
      当我们使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。

    3.3.2 IOC中 bean 标签和管理对象细节

    3.3.2.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。

    3.3.2.2 bean 的作用范围和生命周期

    单例对象:scope="singleton"

    一个应用只有一个对象的实例。它的作用范围就是整个引用。

    生命周期:

    • 对象出生:当应用加载,创建容器时,对象就被创建了。
    • 对象活着:只要容器在,对象一直活着。
    • 对象死亡:当应用卸载,销毁容器时,对象就被销毁了。

    多例对象:scope="prototype"

    每次访问对象时,都会重新创建对象实例。

    生命周期:

    • 对象出生:当使用对象时,创建新的对象实例。
    • 对象活着:只要对象在使用中,就一直活着。
    • 对象死亡:当对象长时间不用时,被 Java 的垃圾回收器回收了。

    3.3.2.3 实例化 Bean 的三种方式

    第一种方式:使用默认无参构造函数

    复制代码
     <!--在默认情况下: 
      它会根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。  
     --> 
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"/> 
    

    第二种方式:spring管理静态工厂-使用静态工厂的方法创建对象

    复制代码
    //模拟一个静态工厂,创建业务层实现类
    public class StaticFactory {
    	public static AccountService createAccountService() {
    		return new AccountServiceImpl();
    	}
    }
    <!-- 此种方式是: 
      使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入 spring 容器 
      id 属性:指定 bean 的 id,用于从容器中获取 
      class 属性:指定静态工厂的全限定类名 
      factory-method 属性:指定生产对象的静态方法 
    --> 
    <bean id="accountService"  
       class="com.itheima.factory.StaticFactory"  
       factory-method="createAccountService"></bean> 
    

    第三种方式:spring管理实例工厂-使用实例工厂的方法创建对象

    复制代码
    /** 
     * 模拟一个实例工厂,创建业务层实现类 
     * 此工厂创建对象,必须现有工厂实例对象,再调用方法  
     */
    public class InstanceFactory {
    	public AccountService createAccountSerivce() {
    		return new AccountServiceImpl();
    	}
    }
    
    <!-- 此种方式是: 
         先把工厂的创建交给 spring 来管理。 
         然后在使用工厂的 bean 来调用里面的方法 
         factory-bean 属性:用于指定实例工厂 bean 的 id。 
         factory-method 属性:用于指定实例工厂中创建对象的方法。 
    --> 
     <bean id="instancFactory" class="com.itheima.factory.InstanceFactory"></bean>
     <bean id="accountService"  
        factory-bean="instancFactory"  
        factory-method="createAccountService"></bean> 
    

    3.3.3 spring的依赖注入

    3.3.3.1 依赖注入的概念

    依赖注入:Dependency Injection。它是 spring 框架核心 ioc 的具体实现。

    我们的程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。 ioc 解耦只是降低他们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。

    那这种业务层和持久层的依赖关系,在使用 spring 之后,就让 spring 来维护了。 简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。

    3.3.3.2 构造函数注入

    顾名思义,就是使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置的方式,让 spring 框架来为我们注入。具体代码如下:

    复制代码
    public class AccountServiceImpl1 implements AccountService {
    	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() {
    		System.out.println();
    	}
    }
    
    <!-- 使用构造函数的方式,给 service 中的属性传值 
    	要求: 
    		类中需要提供一个对应参数列表的构造函数。 
    	涉及的标签: 
    		constructor-arg
    			属性:
    				index:指定参数在构造函数参数列表的索引位置 
    				type:指定参数在构造函数中的数据类型 
    				name:指定参数在构造函数中的名称     用这个找给谁赋值 
    				=======上面三个都是找给谁赋值,下面两个指的是赋什么值的============== 
    				value:它能赋的值是基本数据类型和 String 类型 
    				ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean 
    --> 
    
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl1">
    	<constructor-arg name="name" value="张三"></constructor-arg>
    	<constructor-arg name="age" value="18"></constructor-arg> 
    	<constructor-agr> name="birthday" ref="now"></constructor-arg> 
    </bean>
    
    <bean id="now" class="java.util.Date"></bean>
    

    3.3.3.3 set方法注入

    顾名思义,就是在类中提供需要注入成员的 set 方法。具体代码如下:

    复制代码
    public class AccountServiceImpl2 implements AccountService {
    	private String name;
    	private Integer age;
    	private Date birthday;
    	
    	public void setName(String name) {
    		this.name = name;
    	}
    	public void setAge(Integer age) {
    		this.age = age;
    	}
    	public void setBirthday(Date birthday) {
    		this.birthday = birthday;
    	}
    	@Override
    	public void saveAccount() {
    		System.out.println(name+","+age+","+birthday);
    	}
    }
    
    <!-- 通过配置文件给 bean 中的属性传值:使用 set 方法的方式 
    	涉及的标签: 
    		property 
    			属性: 
    				name:找的是类中 set 方法后面的部分 
    				ref:给属性赋值是其他 bean 类型的 
    				value:给属性赋值是基本数据类型和 string 类型的 
    		实际开发中,此种方式用的较多。 
    -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl2"> 
    	<property name="name" value="test"></property>
    	<property name="age" value="21"></property> 
    	<property name="birthday" ref="now"></property> 
    </bean> 
    <bean id="now" class="java.util.Date"></bean> 
    

    3.3.3.4 使用 p 名称空间注入数据(本质还是调用 set 方法)

    此种方式是通过在 xml中导入 p名称空间,使用 p:propertyName 来注入数据,它的本质仍然是调用类中的 set 方法实现注入功能。

    Java代码(和set注入相同):

    复制代码
    public class AccountServiceImpl3 implements AccountService {
    	private String name;
    	private Integer age;
    	private Date birthday;
    	
    	public void setName(String name) {
    		this.name = name;
    	}
    	public void setAge(Integer age) {
    		this.age = age;
    	}
    	public void setBirthday(Date birthday) {
    		this.birthday = birthday;
    	}
    	@Override
    	public void saveAccount() {
    		System.out.println(name+","+age+","+birthday);
    	}
    }
    

    配置文件代码(需要添加p的约束):

    复制代码
    <beans xmlns="http://www.springframework.org/schema/beans" 
    	   xmlns:p="http://www.springframework.org/schema/p" 
    	   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"> 
    	<bean id="accountService"  
     		  class="com.itheima.service.impl.AccountServiceImpl3" 
    		  p:name="test" p:age="21" p:birthday-ref="now"/> 
    	<bean id="now" class="java.util.Date"></bean>
    </beans>
    

    3.3.3.5 注入集合属性

    顾名思义,就是给类中的集合成员传值,它用的也是set方法注入的方式,只不过变量的数据类型都是集合。 我们这里介绍注入数组,List,Set,Map,Properties。具体代码如下:

    复制代码
    public class AccountServiceImpl4 implements AccountService {
    	private String[] myStrs;
    	private List<String> myList;
    	private Set<String> mySet;
    	private Map<String,String> myMap;
    	private Properties myProps;
    
    	public void setMyStrs(String[] myStrs) {
    		this.myStrs = myStrs;
    	}
    	public void setMyList(List<String> myList) {
    		this.myList = myList;
    	}
    	public void setMySet(Set<String> mySet) {
    		this.mySet = mySet; 
     	}
    	public void setMyMap(Map<String,String> myMap) {
     		this.myMap = myMap;
    	}
    	public void setMyProps(Properties myProps) {
    		this.myProps = myProps;
    	}
    
    	@Override
    	public void saveAccount() {
    		//省略...
    	}
    }
    
    <!-- 注入集合数据 
    	List 结构的: 
    		array,list,set 
    	Map 结构的 
    		map,entry,props,prop 
    -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> 
    	<!-- 在注入集合数据时,只要结构相同,标签可以互换 --> 
    	<!-- 给数组注入数据 --> 
    	<property name="myStrs"> 
    		<set> 
    			<value>AAA</value>
    			<value>BBB</value>
    			<value>CCC</value>
    		</set>
    	</property>
    	<!-- 注入List集合数据 --> 
    	<property name="myList"> 
    		<array> 
    			<value>AAA</value>
    			<value>BBB</value>
    			<value>CCC</value>
    		</array>
    	</property>
    	<!-- 注入Set集合数据 --> 
    	<property name="mySet"> 
    		<list> 
    			<value>AAA</value>
    			<value>BBB</value>
    			<value>CCC</value>
    		</list>
    	</property>
    	<!-- 注入Map数据 --> 
    	<property name="myMap"> 
    		<props> 
    			<prop key="testA">aaa</prop>
    			<prop key="testB">bbb</prop>
    		</props>
    	</property>
    	<!-- 注入properties数据 --> 
    	<property name="myProps"> 
    		<map> 
    			<entry key="testA" value="aaa"></entry>
    			<entry key="testB">
    				<value>bbb</value>
    			</entry>
    		</map>
    	</property>
    </bean>
    

    第4章 案例:使用 spring 的 IoC的实现账户的 CRUD

    4.1 需求和技术要求

    需求:实现账户的 CRUD 操作

    技术要求:

    • 使用 spring 的 IoC 实现对象的管理
    • 使用 QueryRunner 作为持久层解决方案
    • 使用 c3p0 数据源

    4.2 编写代码

    4.2.1 创建数据库和编写实体类

    复制代码
    create table account(
      id int primary key auto_increment,
      name varchar(40),
      money float
    )character set utf8 collate utf8_general_ci; 
    
    insert into account(name,money) values('aaa',1000); 
    insert into account(name,money) values('bbb',1000); 
    insert into account(name,money) values('ccc',1000); 
    
    //账户的实体类
    public class Account implements Serializable {
    	private Integer id;
    	private String name;
    	private Float money;
    	//三个属性的getter/setter方法 在此省略
    }
    

    4.2.2 编写持久层代码

    复制代码
    //账户的持久层接口
    public interface AccountDao {
        /**
         * 查询所有
         * @return
         */
        List<Account> findAllAccount();
    
        /**
         * 查询一个
         * @return
         */
        Account findAccountById(Integer accountId);
    
        /**
         * 保存
         * @param account
         */
        void saveAccount(Account account);
    
        /**
         * 更新
         * @param account
         */
        void updateAccount(Account account);
    
        /**
         * 删除
         * @param acccountId
         */
        void deleteAccount(Integer acccountId);
    }
    
    
    //账户的持久层实现类
    public class AccountDaoImpl implements AccountDao {
    
        private QueryRunner runner;
    
        public void setRunner(QueryRunner runner) {
            this.runner = runner;
        }
    
        @Override
        public List<Account> findAllAccount() {
            try{
                return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public Account findAccountById(Integer accountId) {
            try{
                return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void saveAccount(Account account) {
            try{
                runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
            }catch (Exception 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 (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void deleteAccount(Integer accountId) {
            try{
                runner.update("delete from account where id=?",accountId);
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    

    4.2.3 编写业务层代码

    复制代码
    //账户的业务层接口
    public interface AccountService {
        /**
         * 查询所有
         * @return
         */
        List<Account> findAllAccount();
    
        /**
         * 查询一个
         * @return
         */
        Account findAccountById(Integer accountId);
    
        /**
         * 保存
         * @param account
         */
        void saveAccount(Account account);
    
        /**
         * 更新
         * @param account
         */
        void updateAccount(Account account);
    
        /**
         * 删除
         * @param acccountId
         */
        void deleteAccount(Integer acccountId);
    }
    
    
    //账户的业务层实现类
    public class AccountServiceImpl implements AccountService{
    
        private IAccountDao accountDao;
    
        public void setAccountDao(IAccountDao accountDao) {
            this.accountDao = accountDao;
        }
    
        @Override
        public List<Account> findAllAccount() {
            return accountDao.findAllAccount();
        }
    
        @Override
        public Account findAccountById(Integer accountId) {
            return accountDao.findAccountById(accountId);
        }
    
        @Override
        public void saveAccount(Account account) {
            accountDao.saveAccount(account);
        }
    
        @Override
        public void updateAccount(Account account) {
            accountDao.updateAccount(account);
        }
    
        @Override
        public void deleteAccount(Integer acccountId) {
            accountDao.deleteAccount(acccountId);
        }
    }
    

    4.2.4 创建并编写配置文件

    在resource下创建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">
        <!-- 配置Service -->
        <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
            <!-- 注入dao -->
            <property name="accountDao" ref="accountDao"></property>
        </bean>
    
        <!--配置Dao对象-->
        <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
            <!-- 注入QueryRunner -->
            <property name="runner" ref="runner"></property>
        </bean>
    
        <!--配置QueryRunner-->
        <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
            <!--注入数据源-->
            <constructor-arg name="ds" ref="dataSource"></constructor-arg>
        </bean>
    
        <!-- 配置数据源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!--连接数据库的必备信息-->
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
    </beans>
    

    4.3 测试案例

    4.3.1 测试类代码

    复制代码
    public class AccountServiceTest {
    
        @Test
        public void testFindAll() {
            //1.获取容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.得到业务层对象
            IAccountService as = ac.getBean("accountService",IAccountService.class);
            //3.执行方法
            List<Account> accounts = as.findAllAccount();
            for(Account account : accounts){
                System.out.println(account);
            }
        }
    
        @Test
        public void testFindOne() {
            //1.获取容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.得到业务层对象
            IAccountService as = ac.getBean("accountService",IAccountService.class);
            //3.执行方法
            Account account = as.findAccountById(1);
            System.out.println(account);
        }
    
        @Test
        public void testSave() {
            Account account = new Account();
            account.setName("test");
            account.setMoney(12345f);
            //1.获取容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.得到业务层对象
            IAccountService as = ac.getBean("accountService",IAccountService.class);
            //3.执行方法
            as.saveAccount(account);
    
        }
    
        @Test
        public void testUpdate() {
            //1.获取容易
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.得到业务层对象
            IAccountService as = ac.getBean("accountService",IAccountService.class);
            //3.执行方法
            Account account = as.findAccountById(4);
            account.setMoney(23456f);
            as.updateAccount(account);
        }
    
        @Test
        public void testDelete() {
            //1.获取容易
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.得到业务层对象
            IAccountService as = ac.getBean("accountService",IAccountService.class);
            //3.执行方法
            as.deleteAccount(4);
        }
    }
    

    4.3.2 分析测试中的问题

    通过上面的测试类,我们可以看出,每个测试方法都重新获取了一次 spring 的核心容器,造成了不必要的重复代码,增加了我们开发的工作量。这种情况,在开发中应该避免发生。

    当然我们可以把容器的获取定义到类中去。例如:

    复制代码
    public class AccountServiceTest { 
    	private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
    	private AccountService as = ac.getBean("accountService",AccountService.class); 
    }
    

    这种方式虽然能解决问题,但是仍需要我们自己写代码来获取容器。能不能测试时直接就编写测试方法,而不需要手动编码来获取容器呢? 可以在第6章找到答案。

    第5章 基于注解的IOC配置

    5.1 明确:写在最前

    注解配置和 xml 配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。

    关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯。所以这两种配置方式我们都需要掌握。

    在学习注解配置时,采用上一章节的案例,把 spring 的 xml 配置内容改为使用注解逐步实现。

    5.2 使用注解配置管理的资源

    复制代码
    @Service("accountService")
    public class AccountServiceImpl implements AccountService{
    
        @Autowired
        private IAccountDao accountDao;
    	//省略...
    }
    
    @Repository("accountDao")
    public class AccountDaoImpl implements IAccountDao {
    
        @Autowired
        private QueryRunner runner;
    	//省略...
    }
    

    5.3 修改bean.xml开启对注解的支持

    注意: 基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <!-- 告知spring在创建容器时要扫描注解的包 -->
        <context:component-scan base-package="com.itheima"></context:component-scan>
        <!--配置QueryRunner-->
        <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
            <!--注入数据源-->
            <constructor-arg name="ds" ref="dataSource"></constructor-arg>
        </bean>
    
        <!-- 配置数据源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!--连接数据库的必备信息-->
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
            <property name="user" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
    </beans>
    

    5.4 常用注解

    5.4.1 用于创建对象的

    相当于:<bean id="" class="">

    5.4.1.1 @Component

    作用:
    把资源让 spring 来管理。相当于在 xml 中配置一个 bean。

    属性:
    value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。

    5.4.1.2 @Controller @Service @Repository

    他们三个注解都是针对@Component的衍生注解,他们的作用及属性都是一模一样的。

    他们只不过是提供了更加明确的语义化。

    • @Controller:一般用于表现层的注解。
    • @Service:一般用于业务层的注解。
    • @Repository:一般用于持久层的注解。

    细节:如果注解中有且只有一个属性要赋值时,且名称是 value,value在赋值是可以不写。

    5.4.2 用于注入数据的

    相当于:<property name="" ref=""> <property name="" value="">

    5.4.2.1 @Autowired

    作用:

    自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他 bean 类型。当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到就报错。

    5.4.2.2 @Qualifier

    作用:

    在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowire 一起使用;但是给方法参数注入时,可以独立使用。

    属性:

    value:指定 bean 的 id。

    5.4.2.3 @Resource

    作用:

    直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。

    属性:

    name:指定 bean 的 id。

    5.4.2.4 @Value

    作用:

    注入基本数据类型和 String 类型数据的

    属性:

    value:用于指定值

    5.4.3 用于改变作用范围的

    相当于:<bean id="" class=""scope=""/>

    5.4.3.1 @Scope

    作用:

    指定 bean 的作用范围。

    属性:

    value: 指定范围的值

    取值:singleton prototype request session globalsession

    5.4.4 和生命周期相关的(了解)

    相当于:<bean id="" class=""init-method="" destroy-method=""/>

    5.4.4.1 @PostConstruct

    作用: 用于指定初始化方法。

    5.4.4.2 @PreDestroy

    作用: 用于指定销毁方法。

    5.4.5 关于 Spring 注解 和 XML 的选择问题

    • 注解的优势
      • 配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。
    • XML的优势
      • 修改时,不用改源码。不涉及重新编译和部署。
    • Spring管理Bean方式的比较:

    5.5 spring管理对象细节

    基于注解的 spring IoC 配置中,bean 对象的特点和基于 XML 配置是一模一样的。

    5.6 spring的纯注解配置

    写到此处,基于注解的 IoC 配置已经完成,但是我们依然离不开 spring 的 xml 配置文件,那么能不能不写这个 bean.xml,所有配置都用注解来实现呢?

    5.6.1 待改造的问题

    我们发现,之所以我们现在离不开 xml 配置文件,是因为我们有一句很关键的配置:

    复制代码
    <!-- 告知spring在创建容器时要扫描注解的包 -->
    <context:component-scan base-package="com.itheima"></context:component-scan>
    

    如果它要也能用注解配置,那么我们就离脱离 xml 文件又进了一步。

    另外数据源和QueryRunner的配置也需要靠注解来实现。

    复制代码
        <!--配置QueryRunner-->
        <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
            <!--注入数据源-->
            <constructor-arg name="ds" ref="dataSource"></constructor-arg>
        </bean>
    
        <!-- 配置数据源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!--连接数据库的必备信息-->
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
            <property name="user" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
    

    5.6.2 新注解说明

    5.6.2.1 @Configuration

    作用:

    用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用 AnnotationApplicationContext(有@Configuration 注解的类.class)。

    属性:

    value:用于指定配置类的字节码

    示例代码:

    复制代码
    //spring的配置类,相当于bean.xml文件
    @Configuration
    public class SpringConfiguration {
    
    }
    

    注意:

    我们已经把配置文件用类来代替了,但是如何配置创建容器时要扫描的包呢?请看下一个注解。

    5.6.2.2 @ComponentScan

    作用:

    用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的: <context:component-scan base-package="com.itheima"/> 是一样的。

    属性:

    basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。

    示例代码:

    复制代码
    //spring的配置类,相当于bean.xml文件
    @Configuration
    @ComponentScan("com.itheima")
    public class SpringConfiguration {
    
    }
    

    注意:

    我们已经配置好了要扫描的包,但是数据源和 JdbcTemplate 对象如何从配置文件中移除呢?请看下一个注解。

    5.6.2.3 @Bean

    作用:

    该注解只能写在方法上,用于把当前方法的返回值作为bean对象存入spring的ioc容器中。

    属性:

    name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)。当不写时,默认值是当前方法的名称。

    细节:

    当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
    查找的方式和Autowired注解的作用是一样的。

    示例代码:

    复制代码
    public class JdbcConfig {
    
        /**
         * 用于创建一个QueryRunner对象
         * @param dataSource
         * @return
         */
        @Bean(name="runner")
        @Scope("prototype")
        public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
            return new QueryRunner(dataSource);
        }
    
        /**
         * 创建数据源对象
         * @return
         */
    
        @Bean(name="ds1")
        public DataSource createDataSource1(){
            try {
                ComboPooledDataSource ds = new ComboPooledDataSource();
                ds.setDriverClass(driver);
                ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");
                ds.setUser(username);
                ds.setPassword(password);
                return ds;
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
    }
    

    注意:

    我们已经把数据源和 DBAssit 从配置文件中移除了,此时可以删除 bean.xml 了。
    但是由于没有了配置文件,创建数据源的配置又都写死在类中了。如何把它们配置出来呢?
    请看下一个注解。

    5.6.2.4 @PropertySource

    作用:

    用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到 properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。

    属性:

    value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:

    示例代码:

    复制代码
    public class JdbcConfig {
    
        @Value("${jdbc.driver}")
        private String driver;
    
        @Value("${jdbc.url}")
        private String url;
    
        @Value("${jdbc.username}")
        private String username;
    
        @Value("${jdbc.password}")
        private String password;
    
        /**
         * 创建数据源对象
         * @return
         */
        @Bean(name="ds2")
        public DataSource createDataSource(){
            try {
                ComboPooledDataSource ds = new ComboPooledDataSource();
                ds.setDriverClass(driver);
                ds.setJdbcUrl(url);
                ds.setUser(username);
                ds.setPassword(password);
                return ds;
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
    }
    
    jdbc.properties文件:
    	jdbc.driver=com.mysql.jdbc.Driver
    	jdbc.url=jdbc:mysql://localhost:3306/eesy
    	jdbc.username=root
    	jdbc.password=root
    

    注意:

    此时我们已经有了两个配置类,但是他们还没有关系。如何建立他们的关系呢?
    请看下一个注解。

    5.6.2.5 @Import

    作用:

    用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题。

    属性:

    value[]:用于指定其他配置类的字节码。

    示例代码:

    复制代码
    @ComponentScan("com.itheima")
    @Import(JdbcConfig.class)
    @PropertySource("classpath:jdbcConfig.properties")
    public class SpringConfiguration {
    
    }
    

    注意:

    我们已经把要配置的都配置好了,但是新的问题产生了,由于没有配置文件了,如何获取容器呢?
    请看下一小节。

    5.6.2.6 通过注解获取容器

    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);

    配置类和配置文件可以写在类路径下的任意位置

    第6章 Spring整合Junit[掌握]

    6.1 测试类中的问题和解决思路

    6.1.1 问题

    在测试类中,每个测试方法都有以下两行代码:

    复制代码
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    IAccountService as = ac.getBean("accountService",AccountService.class);
    

    这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

    6.1.2 解决思路分析

    针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就无须手动创建了,问题也就解决了。

    我们都知道,junit 单元测试的原理,但显然,junit 是无法实现的,因为它自己都无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在,junit 给我们暴露了一个注解,可以让我们替换掉它的运行器。

    这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。

    6.2 配置步骤

    6.2.1 第一步:使用@RunWith注解替换原有运行器

    复制代码
    @RunWith(SpringJUnit4ClassRunner.class)
    public class AccountServiceTest {
    
    }
    

    6.2.2 第二步:使用@ContextConfiguration指定spring配置文件的位置

    复制代码
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = SpringConfiguration.class)
    public class AccountServiceTest {
    
    }
    
    • @ContextConfiguration 注解:
      • locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明 例如 locations=("classpath:bean.xml")
      • classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。

    6.2.3 第三步:使用@Autowired给测试类中的变量注入数据

    复制代码
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = SpringConfiguration.class)
    public class AccountServiceTest {
    
        @Autowired
        private AccountService as = null;
    }
    

    6.3 为什么到 不把测试类配到 xml 中

    配到xml中肯定是可以使用的。

    那么为什么不采用配置到 xml 中的方式呢?

    这个原因是这样的:

    第一:当我们在 xml 中配置了一个 bean,spring 加载配置文件创建容器时,就会创建对象。

    第二:测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问题,所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费。

    所以,基于以上两点,我们不应该把测试配置到 xml 文件中。

    第7章 AOP的相关概念[理解]

    7.1 AOP概述

    7.1.1 什么是AOP

    AOP:全称是 Aspect Oriented Programming 即:面向切面编程。

    简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。

    7.1.2 AOP的作用及优势

    作用:

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

    优势:

    • 减少重复代码
    • 提高开发效率
    • 维护方便

    7.1.3 AOP的实现方式

    使用动态代理技术

    7.2 AOP的具体应用

    7.2.1 案例中的问题

    在第4章实现账户的 CRUD 案例中,其实是存在问题的,问题就是:

    事务被自动控制了。换言之,我们使用了 connection 对象的 setAutoCommit(true)

    此方式控制事务,如果我们每次都执行一条 sql 语句,没有问题,但是如果业务方法一次要执行多条 sql 语句,这种方式就无法实现功能了。

    请看下面的示例: 我们在业务层中多加入一个方法。

    复制代码
    业务层接口
    
    void transfer(String sourceName,String targetName,Float money);
    
    业务层实现类
    
    @Override 
    public void transfer(String sourceName, String targetName, Float money) { 
    	//根据名称查询两个账户信息 
    	Account source = accountDao.findByName(sourceName); 
    	Account target = accountDao.findByName(targetName); 
    	//转出账户减钱,转入账户加钱 
    	source.setMoney(source.getMoney()-money); 
    	target.setMoney(target.getMoney()+money); 
    	//更新两个账户 
    	accountDao.update(source); 
    	int i=1/0; //模拟转账异常 
    	accountDao.update(target); 
    } 
    

    当我们执行时,由于执行有异常,转账失败。但是因为我们是每次执行持久层方法都是独立事务,导致无法实现事务控制(不符合事务的一致性)。会导致第一个账户钱减少,但第二个账户钱未增加。

    7.2.2 问题的解决

    解决办法:

    添加一个事务控制类,让业务层来控制事务的提交和回滚。

    TransactionManager 类的代码:

    复制代码
    /**
     * 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
     */
    public class TransactionManager {
    
        private ConnectionUtils connectionUtils;
    
        public void setConnectionUtils(ConnectionUtils connectionUtils) {
            this.connectionUtils = connectionUtils;
        }
    
        /**
         * 开启事务
         */
        public  void beginTransaction(){
            try {
                connectionUtils.getThreadConnection().setAutoCommit(false);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
        /**
         * 提交事务
         */
        public  void commit(){
            try {
                connectionUtils.getThreadConnection().commit();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
        /**
         * 回滚事务
         */
        public  void rollback(){
            try {
                connectionUtils.getThreadConnection().rollback();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
    
        /**
         * 释放连接
         */
        public  void release(){
            try {
                connectionUtils.getThreadConnection().close();//还回连接池中
                connectionUtils.removeConnection();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    

    改造业务层实现类(此处没有使用spring的Ioc)

    复制代码
    /**
     * 账户的业务层实现类
     *
     * 事务控制应该都是在业务层
     */
    public class AccountServiceImpl_OLD implements AccountService{
    
        private AccountDao accountDao;
        private TransactionManager txManager;
    
        public void setTxManager(TransactionManager txManager) {
            this.txManager = txManager;
        }
    
        public void setAccountDao(IAccountDao accountDao) {
            this.accountDao = accountDao;
        }
    
        @Override
        public List<Account> findAllAccount() {
            try {
                //1.开启事务
                txManager.beginTransaction();
                //2.执行操作
                List<Account> accounts = accountDao.findAllAccount();
                //3.提交事务
                txManager.commit();
                //4.返回结果
                return accounts;
            }catch (Exception e){
                //5.回滚操作
                txManager.rollback();
                throw new RuntimeException(e);
            }finally {
                //6.释放连接
                txManager.release();
            }
        }
    	//其他方法此处省略,添加事务控制方法相同。
    }
    

    7.2.3 新的问题

    上一小节的代码,通过对业务层改造,已经可以实现事务控制了,但是由于我们添加了事务控制,也产生了一个新的问题:

    业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了。

    试想一下,如果我们此时提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码,况且这还只是一个业务层实现类,而实际的项目中这种业务层实现类可能有十几个甚至几十个。

    我们可以使用动态代理解决这个问题

    7.2.4 动态代理

    7.2.4.1 动态代理的特点

    字节码随用随创建,随用随加载。

    它与静态代理的区别也在于此。因为静态代理是字节码一上来就创建好,并完成加载。

    装饰者模式就是静态代理的一种体现。

    7.2.4.2 动态代理常用的有两种方式

    • 基于接口的动态代理
      • 提供者:JDK 官方的 Proxy 类。
      • 要求:被代理类最少实现一个接口。
    • 基于子类的动态代理
      • 提供者:第三方的 CGLib,如果报 asmxxxx 异常,需要导入 asm.jar。
      • 要求:被代理类不能用 final 修饰的类(最终类)。

    7.2.5 解决案例中的问题

    复制代码
    /**
     * 用于创建Service的代理对象的工厂
     */
    public class BeanFactory {
    
        private IAccountService accountService;
    
        private TransactionManager txManager;
    
        public void setTxManager(TransactionManager txManager) {
            this.txManager = txManager;
        }
    
    
        public final void setAccountService(IAccountService accountService) {
            this.accountService = accountService;
        }
    
        /**
         * 获取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 {
    
                            if("test".equals(method.getName())){
                                return method.invoke(accountService,args);
                            }
    
                            Object rtValue = null;
                            try {
                                //1.开启事务
                                txManager.beginTransaction();
                                //2.执行操作
                                rtValue = method.invoke(accountService, args);
                                //3.提交事务
                                txManager.commit();
                                //4.返回结果
                                return rtValue;
                            } catch (Exception e) {
                                //5.回滚操作
                                txManager.rollback();
                                throw new RuntimeException(e);
                            } finally {
                                //6.释放连接
                                txManager.release();
                            }
                        }
                    });
        }
    }
    

    当我们改造完成之后,业务层用于控制事务的重复代码就都可以删掉了。

    第8章 Spring中的AOP[掌握]

    8.1 Spring中AOP的细节

    8.1.1 说明

    学习 spring 的 aop,就是通过配置的方式,实现上一章节的功能。

    8.1.2 AOP相关术语

    • Joinpoiont(连接点)

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

    • Pointcut(切入点)

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

    • Advice(通知/增强)

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

      通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。

    • Introduction(引介)

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

    • Target(目标对象)

      代理的目标对象。

    • Weaving(织入)

      是指把增强应用到目标对象来创建新的代理对象的过程。

      spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。

    • Proxy(代理)

      一个类被 AOP 织入增强后,就产生一个结果代理类。

    • Aspect(切面)

      是切入点和通知(引介)的结合。

    8.1.3 学习spring中的AOP要明确的事

    a、开发阶段(我们做的)

    编写核心业务代码(开发主线)

    把公用代码抽取出来,制作成通知。(开发阶段最后再做)

    配置文件中,声明切入点与通知间的关系,即切面。

    b、运行阶段(Spring框架完成的)

    Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。

    8.1.4 关于代理的选择

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

    8.2 基于XML的AOP配置

    在学习 spring 的 aop 时,采用一个简单的账户案例作为示例。并且把 spring 的 ioc 也一起应用进来。此处只为展示AOP的配置方式所有不与数据库进行交互。

    8.2.1 环境搭建

    8.2.1.1 第一步:pom.xml中添加依赖

    复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
    </dependencies>
    

    8.2.1.2 第二步:创建spring的配置文件bean.xml并导入约束

    此处要导入 aop 的约束

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

    8.2.1.3 第三步:配置spring的ioc

    复制代码
    <!-- 配置srping的Ioc,把service对象配置进来-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    

    8.2.1.4 第四步:创建通知类

    复制代码
    /**
     * 用于记录日志的工具类,它里面提供了公共的代码
     */
    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方法开始记录日志了。。。");
        }
    
        /**
         * 环绕通知
         * 问题:
         *      当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
         * 分析:
         *      通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
         * 解决:
         *      Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
         *      该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
         *
         * spring中的环绕通知:
         *      它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
         */
        public Object aroundPrintLog(ProceedingJoinPoint pjp){
            Object rtValue = null;
            try{
                Object[] args = pjp.getArgs();//得到方法执行所需的参数
                System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");
                rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
                System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");
                return rtValue;
            }catch (Throwable t){
                System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
                throw new RuntimeException(t);
            }finally {
                System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
            }
        }
    }
    

    8.2.2 配置步骤

    8.2.2.1 第一步:把通知类用 bean 标签配置起来

    复制代码
    <!-- 配置Logger类 -->
    <bean id="logger" class="com.itheima.utils.Logger"></bean>
    

    8.2.2.2 第二步:使用 aop:config 声明 aop 配置

    aop:config

    作用:用于声明开始 aop 的配置。

    复制代码
    <aop:config>
    	<!-- 配置的代码都写在此处 -->
    </aop:config>
    

    8.2.2.3 第三步:使用 aop:aspect 配置切面

    aop:aspect

    作用:用于配置切面。

    属性:

    • id:给切面提供一个唯一标识。

    • ref:引用配置好的通知类 bean 的 id。

      <aop:aspect id="logAdvice" ref="logger">

      </aop:aspect>

    8.2.2.4 第四步:使用 aop:pointcut 配置切入点表达式

    aop:pointcut

    作用:用于配置切入点表达式,就是指定对哪些类的哪些方法进行增强。

    属性:

    • expression:用于定义切入点表达式。
    • id:用于给切入点表达式提供一个唯一标识

    此标签写在aop:aspect标签内部只能当前切面使用。
    它还可以写在aop:aspect外面,此时就变成了所有切面可用

    复制代码
    <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
    

    8.2.2.5 第五步: 使用 aop:xxx 配置对应的通知类型

    aop:before

    作用:用于配置前置通知,指定增强的方法在切入点方法之前执行。

    属性:

    • method:用于指定通知类中的增强方法名称
    • ponitcut-ref:用于指定切入点的表达式的引用
    • poinitcut:用于指定切入点表达式

    执行时间点:
    切入点方法执行之前执行

    复制代码
    <aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>
    

    aop:after-returning

    作用:用于配置后置通知

    属性:

    • method:用于指定通知类中的增强方法名称
    • ponitcut-ref:用于指定切入点的表达式的引用
    • poinitcut:用于指定切入点表达式

    执行时间点:
    切入点方法正常执行之后执行。它和异常通知只能有一个执行。

    复制代码
    <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
    

    aop:after-throwing

    作用:用于配置异常通知

    属性:

    • method:用于指定通知类中的增强方法名称
    • ponitcut-ref:用于指定切入点的表达式的引用
    • poinitcut:用于指定切入点表达式

    执行时间点:
    切入点方法执行产生异常后执行。它和后置通知只能执行一个。

    复制代码
    <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
    

    aop:after

    作用:用于配置最终通知

    属性:

    • method:用于指定通知类中的增强方法名称
    • ponitcut-ref:用于指定切入点的表达式的引用
    • poinitcut:用于指定切入点表达式

    执行时间点:

    无论切入点方法执行时是否有异常,它都会在其后面执行。

    复制代码
    aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
    

    8.2.3 切入点表达式说明

    execution:匹配方法的执行(常用)

    execution(表达式)

    表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))

    写法说明:

    • 全匹配方式
      • public void com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
    • 访问修饰符可以省略
      • void com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
    • 返回值可以使用*号,表示任意返回值
      • * com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
    • 包名可以使用号,表示任意包,但是有几级包,需要写几个
      • * *.*.*.*.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
    • 使用..来表示当前包,及其子包
      • * com..AccountServiceImpl.saveAccount(com.itheima.domain.Account)
    • 类名可以使用*号,表示任意类
      • * com..*.saveAccount(com.itheima.domain.Account)
    • 方法名可以使用*号,表示任意方法
      • * com..*.*( com.itheima.domain.Account)
    • 参数列表可以使用*,表示参数可以是任意数据类型,但是必须有参数
      • * com..*.*(*)
    • 参数列表可以使用..表示有无参数均可,有参数可以是任意类型
      • * com..*.*(..)
    • 全通配方式
      • * *..*.*(..)

    注:

    通常情况下,我们都是对业务层的方法进行增强,所以切入点表达式都是切到业务层实现类。

    execution(* com.itheima.service.impl.*.*(..))

    8.2.4 环绕通知

    复制代码
    <aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>
    

    aroundPrintLog方法具体注释在通知类中

    aop:around :

    作用:用于配置环绕通知

    属性:

    • method:用于指定通知类中的增强方法名称
    • ponitcut-ref:用于指定切入点的表达式的引用
    • poinitcut:用于指定切入点表达式

    说明:

    它是 spring 框架为我们提供的一种可以在代码中手动控制增强代码什么时候执行的方式。

    注意:

    通常情况下,环绕通知都是独立使用的

    8.3 基于注解的AOP配置

    8.3.1 环境搭建

    8.3.1.1 第一步:和 准备必要的代码和配置pom.xml

    利于基于XML的AOP配置中的代码及pom.xml即可

    8.3.1.2 第二步:在配置文件中导入 context 的名称空间

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

    8.3.1.3 第三步:把资源使用注解配置

    复制代码
    /**
     * 账户的业务层实现类
     */
    @Service("accountService")
    public class AccountServiceImpl implements IAccountService{
    
    }
    

    8.3.1.4 第四步:在配置文件中指定 spring 要扫描的包

    复制代码
    <!-- 配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
    

    8.3.2 配置步骤

    8.3.2.1 第一步:把通知类也使用注解配置

    复制代码
    @Component("logger")
    public class Logger {
    
    }
    

    8.3.2.2 第二步:在通知类上使用@Aspect 注解声明为切面

    作用:

    把当前类声明为切面类。

    复制代码
    @Component("logger")
    @Aspect//表示当前类是一个切面类
    public class Logger {
    
    }
    

    8.3.2.3 第三步:在增强的方法上使用注解配置通知

    @Before

    作用:把当前方法看成是前置通知。

    属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。

    复制代码
    /**
     * 前置通知
     */
    @Before("execution(* com.itheima.service.impl.*.*(..))")
    public  void beforePrintLog(){
        System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");
    }
    

    @AfterReturning

    作用:把当前方法看成是后置通知。

    属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。

    复制代码
    /**
     * 后置通知
     */
    @AfterReturning("execution(* com.itheima.service.impl.*.*(..))")
    public  void afterReturningPrintLog(){
        System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");
    }
    

    @AfterThrowing

    作用:把当前方法看成是异常通知。

    属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。

    复制代码
    /**
     * 异常通知
     */
    @AfterThrowing("execution(* com.itheima.service.impl.*.*(..))")
    public  void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");
    }
    

    @After

    作用:把当前方法看成是最终通知。

    属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。

    复制代码
    /**
     * 最终通知
     */
    @After("execution(* com.itheima.service.impl.*.*(..))")
    public  void afterPrintLog(){
        System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");
    }
    

    8.3.2.4 第四步:在 spring 配置文件中开启 spring 对注解 AOP 的支持

    复制代码
    <!-- 配置spring开启注解AOP的支持 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    

    8.3.3 环绕通知注解配置

    @Around

    作用:把当前方法看成是环绕通知。

    属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。

    复制代码
    @Around("execution(* com.itheima.service.impl.*.*(..))")
    public Object aroundPringLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();//得到方法执行所需的参数
    
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");
    
            rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
    
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");
    
            return rtValue;
        }catch (Throwable t){
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
            throw new RuntimeException(t);
        }finally {
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
        }
    }
    

    8.3.4 切入点表达式注解

    @Pointcut

    作用:指定切入点表达式

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

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

    引用方式:

    原环绕通知注释

    复制代码
    @Around("execution(* com.itheima.service.impl.*.*(..))")
    

    在设置Pointcut后,与上面作用相同。

    复制代码
    @Around("pt1()")//注意,千万别忘了写括号
    

    8.3.5 不使用XML的配置方式

    复制代码
    @Configuration
    @ComponentScan(basePackages="com.itheima")
    @EnableAspectJAutoProxy	//开启 spring 对注解 AOP 的支持
    public class SpringConfiguration {
    }
    

    第9章 Spring 中的 JdbcTemplate[会用]

    9.1 JdbcTemplate 概述

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

    • 操作关系型数据的:
      • JdbcTemplate
      • HibernateTemplate
    • 操作 nosql 数据库的:
      • RedisTemplate
    • 操作消息队列的:
      • JmsTemplate

    9.2 JdbcTemplate 对象的创建

    我们可以参考它的源码,来一探究竟:

    复制代码
    public JdbcTemplate() {
    }
    public JdbcTemplate(DataSource dataSource) {
    	setDataSource(dataSource);
    	afterPropertiesSet();
    }
    public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
    	setDataSource(dataSource);
    	setLazyInit(lazyInit);
    	afterPropertiesSet();
    }
    

    除了默认构造函数之外,都需要提供一个数据源。既然有set方法,依据我们之前学过的依赖注入,我们可以在配置文件中配置这些对象。

    9.3 spring 中配置数据源

    9.3.1 环境搭建

    pom.xml中添加以下依赖

    复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    </dependencies>
    

    9.3.2 编写spring的配置文件

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    </beans>
    

    9.3.3 配置数据源

    可以使用C3P0和DBCP,当然spring 框架也提供了一个内置数据源,此处我们使用 spring 的内置数据源。

    复制代码
    <!-- 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    

    9.3.4 将数据库连接的信息配置到属性文件中

    【定义属性文件】jdbc.properties

    复制代码
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/eesy
    jdbc.username=root
    jdbc.password=root
    

    【引入外部的属性文件】

    一种方式:

    复制代码
    <!-- 引入外部属性文件: -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	<property name="location" value="classpath:jdbc.properties"/>
    </bean>
    

    另一种方式:

    复制代码
    <context:property-placeholder location="classpath:jdbc.properties"/>
    

    9.4 JdbcTemplate 的增删查改操作

    数据库仍用eesy中的account表

    9.4.1 在 spring 配置文件中配置 JdbcTemplate

    复制代码
    <?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">
    
    	<!-- 配置一个数据库的操作模板: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://localhost:3306/eesy"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
    </beans>
    

    9.4.2 基本的增删查改

    复制代码
    public class JdbcTemplateDemo {
    	public static void main(String[] args) {
    		//1.获取Spring容器
    		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    		//2.根据id获取bean对象
    		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
    		//3.执行操作
    		//插入
    		jt.exeute("insert into account(name,money)values('eee',500)");
    		//保存
    		jt.update("insert into account(name,money)values(?,?)","fff",5000);
    		//修改
    		jt.update("update account set money = money-? where id = ?",300,6)
    		//删除
    		jt.update("delete from account where id = ?",6);
    		//查询所有
    		List<Account> accounts = jt.query("select * from account where money > ? ",new AccountRowMapper(), 500);
    		for(Account o : accounts){
    			System.out.println(o);
    		}
    		//使用 RowMapper 的方式查询一个(常用的方式)
    		List<Account> as = jt.query("select * from account where id = ? ",new AccountRowMapper(), 55);
    		System.out.println(as.isEmpty()?"没有结果":as.get(0));
    		//使用 ResultSetExtractor 的方式查询一个(不常用的方式)
    		Account account = jt.query("select * from account where id = ?",new AccountResultSetExtractor(),3);
    		System.out.println(account);
    		//查询返回一行一列:使用聚合函数,在不使用 group by 字句时,都是返回一行一列。最常用的就是分页中获取总记录条数
    		Integer total = jt.queryForObject("select count(*) from account where money > ?",Integer.class,500);
     		System.out.println(total);
    	}
    }
    
    /**
     * 定义Account的封装策略
     */
    class AccountRowMapper implements RowMapper<Account>{
        /**
         * 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
         * @param rs
         * @param rowNum
         * @return
         * @throws SQLException
         */
        @Override
        public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
            Account account = new Account();
            account.setId(rs.getInt("id"));
            account.setName(rs.getString("name"));
            account.setMoney(rs.getFloat("money"));
            return account;
        }
    }
    

    9.5 在 Dao 中使用 JdbcTemplate

    9.5.1 准备实体类

    复制代码
    //账户的实体
    public class Account implements Serializable {
    	private Integer id;
    	private String name;
    	private Float money;
    	//getter and setter 及 toString 此处省略..
    }
    

    9.5.2 第一种方式:在 dao 中定义 JdbcTemplate

    复制代码
    /**
     * 账户的持久层接口
     */
    public interface IAccountDao {
    
        /**
         * 根据Id查询账户
         * @param accountId
         * @return
         */
        Account findAccountById(Integer accountId);
    
        /**
         * 根据名称查询账户
         * @param accountName
         * @return
         */
        Account findAccountByName(String accountName);
    
        /**
         * 更新账户
         * @param account
         */
        void updateAccount(Account account);
    }
    
    /**
     * 账户的持久层实现类
     * 此版本的 dao ,需要给 dao  注入 JdbcTemplate
     */
    public class AccountDaoImpl2 implements IAccountDao {
    
        private JdbcTemplate jdbcTemplate;
    
    	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    		this.jdbcTemplate = jdbcTemplate;
    	}
    
        @Override
        public Account findAccountById(Integer accountId) {
            List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
            return accounts.isEmpty()?null:accounts.get(0);
        }
    
        @Override
        public Account findAccountByName(String accountName) {
            List<Account> accounts = jdbcTemplate.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
            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());
        }
    }
    

    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">
    
        <!-- 配置账户的持久层-->
        <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
    		<!-- 注入jdbcTemplate -->
            <property name="jdbcTemplate" ref="jdbcTemplate"></property>
            <property name="dataSource" ref="dataSource"></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://localhost:3306/eesy"></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;
    	}
    

    能不能把它抽取出来呢?请看下一小节。

    9.5.3 第二种方式:让 dao 继承 JdbcDaoSupport

    JdbcDaoSupport 是spring 框架为我们提供的一个类,该类中定义了一个 JdbcTemplate 对象,我们可以直接获取使用,但是要想创建该对象,需要为其提供一个数据源:具体源码如下:

    复制代码
    public static class JdbcDaoSupport extends DaoSupport {
    	//定义对象
    	private JdbcTemplate jdbcTemplate;
    	//set方法注入数据源,判断是否注入了,注入了就创建JdbcTemplate
    	public final void setDateSource(DataSource dataSource) {
    		if(this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()){
    			//如果提供了数据源就创建JdbcTemplate
    			this.jdbcTemplate = createJdbcTemplate(dataSource);
    			initTemplateConfig();
    		}
    	}
    	//使用数据源创建JdbcTemplate
    	protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
    		return new JdbcTemplate(dataSource);
    	}
    	//当然我们也可以通过注入JdbcTemplate对象
    	public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    		this.jdbcTemplate = jdbcTemplate;
    		initTemplateConfig();
    	}
    	//使用getJdbcTemplate方法获取操作模板对象
    	public final JdbcTemplate getJdbcTemplate() {
    		return this.jdbcTemplate;
    	}
    }
    
    /**
     * 账户的持久层实现类
     * 此版本dao,只需要给它的父类注入一个数据源
     */
    public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
    
        @Override
        public Account findAccountById(Integer accountId) {
            List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
    		//super.getJdbcTemplate()方法是从父类上继承下来的,直接使用getJdbcTemplate()也一样。
            return accounts.isEmpty()?null:accounts.get(0);
        }
    
        @Override
        public Account findAccountByName(String accountName) {
            List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
            if(accounts.isEmpty()){
                return null;
            }
            if(accounts.size()>1){
                throw new RuntimeException("结果集不唯一");
            }
            return accounts.get(0);
        }
    
        @Override
        public void updateAccount(Account account) {
            super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),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">
    
        <!-- 配置账户的持久层-->
        <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
            <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://localhost:3306/eesy"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
    </beans>
    

    两种Dao的区别:

    • 第一种在 Dao 类中定义 JdbcTemplate 的方式,适用于所有配置方式(xml和注解都可以)。
    • 第二种让 Dao 继承 JdbcDaoSupport 的方式,只能用于基于 XML 的方式,注解用不了。

    第10章 Spring中的事务控制

    10.1 Spring事务控制我们要明确的

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

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

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

    10.2 Spring 中事务控制的API介绍

    10.2.1 PlatformTransactionManager

    此接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法,如下图:

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

    真正管理事务的对象

    • org.springframework.jdbc.datasource.DataSourceTransactionManager
      • 使用 SpringJDBC 或 iBatis 进行持久化数据时使用
    • org.springframework.orm.hibernate5.HibernateTransactionManager
      • 使用Hibernate 版本进行持久化数据时使用

    10.2.2 TransactionDefinition

    它是事务的定义信息对象,里面有如下方法:

    10.2.2.1 事务的隔离级别

    10.2.2.2 事务的传播行为

    • REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
    • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
    • MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
    • REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起
    • NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
    • NEVER:以非事务方式运行,如果当前存在事务,抛出异常
    • NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作

    10.2.2.3 超时时间

    默认值是-1,没有超时限制。如果有,以秒为单位进行设置。

    10.2.2.4 是否是只读事务

    建议查询时设置为只读。

    10.2.3 TransactionStatus

    此接口提供的是事务具体的运行状态,方法介绍如下图:

    10.3 基于 XML 的声明式事务控制(配置方式)[重点]

    10.3.1 环境搭建

    10.3.1.1 第一步:向pom.xml中添加依赖

    复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
    
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    

    10.3.1.2 第二步:创建 spring 的配置文件并导入约束

    此处需要导入aop和tx两个名称空间

    复制代码
    <?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">
    </beans>
    

    10.3.1.3 第三步:准备数据库表和实体类

    继续沿用前面章节使用的eesy数据库的account表以及Account实体类。

    10.3.1.4 第四步:编写业务层接口和实现类

    复制代码
    /**
     * 账户的业务层接口
     */
    public interface IAccountService {
        /**
         * 根据id查询账户信息
         * @param accountId
         * @return
         */
        Account findAccountById(Integer accountId);
    
        /**
         * 转账
         * @param sourceName    转成账户名称
         * @param targetName    转入账户名称
         * @param money         转账金额
         */
        void transfer(String sourceName,String targetName,Float money);
    }
    
    /**
     * 账户的业务层实现类
     *
     * 事务控制应该都是在业务层
     */
    public class AccountServiceImpl implements IAccountService{
    
        private IAccountDao accountDao;
    
        public void setAccountDao(IAccountDao accountDao) {
            this.accountDao = accountDao;
        }
    
        @Override
        public Account findAccountById(Integer accountId) {
            return accountDao.findAccountById(accountId);
    
        }
    
        @Override
        public void transfer(String sourceName, String targetName, Float money) {
            System.out.println("transfer....");
                //2.1根据名称查询转出账户
                Account source = accountDao.findAccountByName(sourceName);
                //2.2根据名称查询转入账户
                Account target = accountDao.findAccountByName(targetName);
                //2.3转出账户减钱
                source.setMoney(source.getMoney()-money);
                //2.4转入账户加钱
                target.setMoney(target.getMoney()+money);
                //2.5更新转出账户
                accountDao.updateAccount(source);
                int i=1/0;
                //2.6更新转入账户
                accountDao.updateAccount(target);
        }
    }
    

    10.3.1.5 第五步:编写 Dao 接口和实现类

    复制代码
    /**
     * 账户的持久层接口
     */
    public interface IAccountDao {
    
        /**
         * 根据Id查询账户
         * @param accountId
         * @return
         */
        Account findAccountById(Integer accountId);
    
        /**
         * 根据名称查询账户
         * @param accountName
         * @return
         */
        Account findAccountByName(String accountName);
    
        /**
         * 更新账户
         * @param account
         */
        void updateAccount(Account account);
    }
    
    /**
     * 账户的持久层实现类
     * 此版本dao,只需要给它的父类注入一个数据源
     */
    public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
    
        @Override
        public Account findAccountById(Integer accountId) {
            List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
            return accounts.isEmpty()?null:accounts.get(0);
        }
    
        @Override
        public Account findAccountByName(String accountName) {
            List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
            if(accounts.isEmpty()){
                return null;
            }
            if(accounts.size()>1){
                throw new RuntimeException("结果集不唯一");
            }
            return accounts.get(0);
        }
    
        @Override
        public void updateAccount(Account account) {
            super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }
    }
    

    这里没有自定义账户的封装类RowMapper而是使用了Spring提供的BeanPropertyRowMapper为Account封装。

    10.3.1.6 第六步:在配置文件中配置业务层和持久层对

    复制代码
    <!-- 配置业务层-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    
    <!-- 配置账户的持久层-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <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://localhost:3306/eesy"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root></property>
    </bean>
    

    10.3.2 配置步骤

    复制代码
    spring中基于XML的声明式事务控制配置步骤
        1、配置事务管理器
        2、配置事务的通知
                此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的
                使用tx:advice标签配置事务通知
                    属性:
                        id:给事务通知起一个唯一标识
                        transaction-manager:给事务通知提供一个事务管理器引用
        3、配置AOP中的通用切入点表达式
        4、建立事务通知和切入点表达式的对应关系
        5、配置事务的属性
               是在事务的通知tx:advice标签的内部
    

    10.3.2.1 第一步: 配置事务管理器

    复制代码
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<!-- 注入DataSource -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    

    10.3.2.2 第二步:配置事务的通知引用事务管理器

    复制代码
    <!-- 配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    </tx:advice>
    

    10.3.2.3 第三步:配置事务的属性

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

    10.3.2.4 第四步:配置 AOP 切入点表达式

    复制代码
    <!-- 配置aop-->
    <aop:config>
        <!-- 配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
    </aop:config>
    

    10.3.2.5 第五步:配置切入点表达式和事务通知的对应关系

    复制代码
    <!-- 在 在 aop:config  标签内部:建立事务的通知和切入点表达式的关系 -->	
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    

    10.4 基于注解的配置方式

    10.4.1 环境搭建

    10.4.1.1 第一步:配置pom.xml

    和基于XML配置相同,略

    10.4.1.2 第二步:创建 spring 的配置文件导入约束并配置扫描的包

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           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.itheima"></context:component-scan>
    
        <!-- 配置JdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!-- 配置spring提供的内置数据源-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
    </beans>
    

    10.4.1.3 第三步:创建数据库表和实体类

    和基于 xml 的配置相同,略

    10.4.1.4 第四步:创建业务层接口和实现类让 并使用注解让 spring 管

    复制代码
    /**
     * 账户的业务层实现类
     *
     * 事务控制应该都是在业务层
     */
    @Service("accountService")
    public class AccountServiceImpl implements IAccountService{
    
        @Autowired
        private IAccountDao accountDao;
    	//其余代码和基于XML的配置相同
    }
    

    10.4.1.5 第五步:创建 Dao 接口和实现类并使用注解让 spring 管理

    复制代码
    /**
     * 账户的持久层实现类
     */
    @Repository("accountDao")
    public class AccountDaoImpl implements IAccountDao {
    
        @Autowired
        private JdbcTemplate jdbcTemplate;
    	//其余代码和基于XML的配置相同
    }
    

    10.4.2 配置步骤

    10.4.2.1 第一步:配置事务管理器并注入数据源

    复制代码
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    

    10.4.2.2 第二步:在业务层使用@Transactional 注解

    复制代码
    @Service("accountService")
    @Transactional(propagation= Propagation.SUPPORTS,readOnly=true)//只读型事务的配置
    public class AccountServiceImpl implements IAccountService{
    
        @Autowired
        private IAccountDao accountDao;
    
        @Override
        public Account findAccountById(Integer accountId) {
            return accountDao.findAccountById(accountId);
    
        }
    
        //需要的是读写型事务配置
        @Transactional(propagation= Propagation.REQUIRED,readOnly=false)
        @Override
        public void transfer(String sourceName, String targetName, Float money) {
            System.out.println("transfer....");
                //2.1根据名称查询转出账户
                Account source = accountDao.findAccountByName(sourceName);
                //2.2根据名称查询转入账户
                Account target = accountDao.findAccountByName(targetName);
                //2.3转出账户减钱
                source.setMoney(source.getMoney()-money);
                //2.4转入账户加钱
                target.setMoney(target.getMoney()+money);
                //2.5更新转出账户
                accountDao.updateAccount(source);
                int i=1/0;
                //2.6更新转入账户
                accountDao.updateAccount(target);
        }
    }
    

    该注解的属性和 xml 中的属性含义一致。该注解可以出现在接口上,类上和方法上。

    出现接口上,表示该接口的所有实现类都有事务支持。

    出现在类上,表示类中所有方法有事务支持

    出现在方法上,表示方法有事务支持。

    以上三个位置的优先级:方法>类>接口

    10.4.2.3 第三步:在配置文件中开启 spring 对注解事务的支持

    复制代码
    <!-- 开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    

    10.4.3 不使用 xml 的配置方式

    复制代码
    /**
     * spring的配置类,相当于bean.xml
     */
    @Configuration
    @ComponentScan("com.itheima")
    @Import({JdbcConfig.class,TransactionConfig.class})
    @PropertySource("jdbcConfig.properties")
    @EnableTransactionManagement
    public class SpringConfiguration {
    }
    
    • @ComponentScan:扫描的包
    • @PropertySource:导入属性资源
    • @EnableTransactionManagement:开启事务支持

    第11章 Spring5 的新特性[了解]

    11.1 与JDK相关的升级

    11.1.1 jdk版本要求

    spring5.0 在 2017 年 9 月发布了它的 GA(通用)版本。该版本是基于 jdk8 编写的,所以 jdk8 以下版本将无法使用。同时,可以兼容 jdk9 版本。

    tomcat 版本要求 8.5 及以上。

    11.1.2 利用jdk8版本更新的内容

    • 基于JDK8的反射增强
      • 在反射创建对象上,jdk8比以前的版本要快很多。
    • @NonNull 注解和@Nullable 注解的使用
      • 用 @Nullable 和 @NotNull 注解来显示表明可为空的参数和以及返回值。这样就够在编译的时候处理空值而不是在运行时抛出
        NullPointerExceptions。
    • 日志记录方面
      • Spring Framework 5.0 带来了 Commons Logging 桥接模块的封装, 它被叫做 spring-jcl 而不是标准的 Commons Logging。当然,无需任何额外的桥接,新版本也会对 Log4j 2.x, SLF4J, JUL(java.util.logging) 进行自动检测。

    11.2 核心容器的更新

    Spring Framework 5.0 现在支持候选组件索引作为类路径扫描的替代方案。该功能已经在类路径扫描器中添加,以简化添加候选组件标识的步骤。

    应用程序构建任务可以定义当前项目自己的 META-INF/spring.components 文件。在编译时,源模型是自包含的,JPA 实体和 Spring 组件是已被标记的。

    从索引读取实体而不是扫描类路径对于小于 200 个类的小型项目是没有明显差异。但对大型项目影响较大。加载组件索引开销更低。因此,随着类数的增加,索引读取的启动时间将保持不变。

    加载组件索引的耗费是廉价的。因此当类的数量不断增长,加上构建索引的启动时间仍然可以维持一个常数,不过对于组件扫描而言,启动时间则会有明显的增长。

    这个对于我们处于大型 Spring 项目的开发者所意味着的,是应用程序的启动时间将被大大缩减。虽然 20或者 30 秒钟看似没什么,但如果每天要这样登上好几百次,加起来就够你受的了。使用了组件索引的话,就能帮
    助你每天过的更加高效。

    你可以在 Spring 的 Jira 上了解更多关于组件索引的相关信息。

    11.3 JetBrains Kotlin 语言支持

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

    11.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));
    

    11.5 Junit5支持

    完全支持 JUnit 5 Jupiter,所以可以使用 JUnit 5 来编写测试以及扩展。此外还提供了一个编程以及扩展模型,Jupiter 子项目提供了一个测试引擎来在 Spring 上运行基于 Jupiter 的测试。

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

    针对响应式编程模型, spring-test 现在还引入了支持 Spring WebFlux 的 WebTestClient 集成测试的支持,类似于 MockMvc,并不需要一个运行着的服务端。使用一个模拟的请求或者响应, WebTestClient就可以直接绑定到 WebFlux 服务端设施。

    你可以在这里找到这个激动人心的 TestContext 框架所带来的增强功能的完整列表。

    当然, Spring Framework 5.0 仍然支持我们的老朋友 JUnit! 在我写这篇文章的时候, JUnit 5 还只是发展到了 GA 版本。对于 JUnit4, Spring Framework 在未来还是要支持一段时间的。

    出处:https://www.cnblogs.com/p1ng/p/12722113.html

  • 相关阅读:
    A component required a bean named xxx that could not be found. Action: Consider defining
    jmeter 配置csv 登陆网站 报错
    动手动脑(文件与流)
    java异常处理总结
    动手动脑(异常处理)
    动手动脑(继承与多态)
    查询对象个数
    动手动脑
    动手动脑
    统计英语文章的单词
  • 原文地址:https://www.cnblogs.com/mq0036/p/12887922.html
Copyright © 2011-2022 走看看