Spring
Spring概述
什么是spring
- Spring是分层的Java SE/EE应用 full-stack 轻量级开源框架,以IOC(反转控制)和AOP(面向切面编程)为内核,提供了展现层Spring MVC和持久层 Spring JDBC以及业务层事务管理等众多企业级应用技术,还能整合开源世界众多著名的第三方框架内库,逐渐成为使用最多的 Java EE企业应用开源框架
spring的优势
- 方便解耦,间接开发
- 通过Spring提供的IOC容器,可以将对象间的依赖关系交由Spring进行控制,避免硬编码造成的过度程度耦合。用户也不必再为单例模式类,属性文件解析等这些很底层的需求编写代码,可以更专注于上层的应用。
- AOP编程的支持
- 通过Spring的AOP功能,方便进行面向切面的编程,许多不容易用传统OOP实现的功能可以通过AOP轻松应对
- 声明式事务的支持
- 可以将我们从单调烦闷的事务管理代码中解脱出来,通过声明式方式灵活的进行事务的管理,提高开发效率和质量。
- 方便程序的测试
- 可以用非容器依赖的编程方式进行几乎所有的的测试工作,测试不再是昂贵的操作。
- 方便继承各种优秀框架
- Spring可以降低各个框架的使用难度,提供了对各个优秀框架(Struts、Hibernate等)的直接支持
- 降低Java EE API的使用难度
- Spring对JavaEE API进行了薄薄的封装,使这些API的使用难度大为降低
- Java 源码是经典的学习案例
- Spring的源代码设计精妙、结构清晰、匠心独用,处处体现着大师对Java 设计模式灵活运用以 及对 Java技术的高深造诣。它的源代码无意是 Java 技术的最佳实践的范例。
spring的体系结构
Ioc的概念和作用
什么是程序的耦合
- 在软件工程中,耦合指的就是就是对象之间的依赖性。对象之间的耦合越高,维护成本越高。因此对象的设计应使类和构件之间的耦合最小。软件设计中通常用耦合度和内聚度作为衡量模块独立程度的标准。划分模块的一个准则就是高内聚低耦合。
- 它有如下分类:
- 内容耦合。当一个模块直接修改或操作另一个模块的数据时,或一个模块不通过正常入口而转入另一个模块,这样的耦合被称为内容耦合。内容耦合是最高程度的耦合,应该避免使用之。
- 公共耦合。两个或两个以上的模块共同引用一个全局数据项,这种耦合被称为公共耦合。在具有大量公共耦合的结构中,确定究竟是哪个模块给全局变量赋了一个特定的值是十分困难的。
- 外部耦合 。一组模块都访问同一全局简单变量而不是同一全局数据结构,而且不是通过参数表传 递该全局变量的信息,则称之为外部耦合。
- 控制耦合 。一个模块通过接口向另一个模块传递一个控制信号,接受信号的模块根据信号值而进 行适当的动作,这种耦合被称为控制耦合。
- 标记耦合 。若一个模块 A 通过接口向两个模块 B 和 C 传递一个公共参数,那么称模块 B 和 C 之间 存在一个标记耦合。
- 数据耦合。模块之间通过参数来传递数据,那么被称为数据耦合。数据耦合是最低的一种耦合形 式,系统中一般都存在这种类型的耦合,因为为了完成一些有意义的功能,往往需要将某些模块的输出数据作为另一些模块的输入数据。
- 非直接耦合 。两个模块之间没有直接关系,它们之间的联系完全是通过主模块的控制和调用来实 现的。
- 总结: 耦合是影响软件复杂程度和设计质量的一个重要因素,在设计上我们应采用以下原则:如果模块间必须存在耦合,就尽量使用数据耦合,少用控制耦合,限制公共耦合的范围,尽量避免使用内容耦合。
解决程序耦合的思路
- 反射+配置文件,减少 new 关键字的使用。
工厂模式解耦
- 在实际开发中我们可以把三层的对象都使用配置文件配置起来,当启动服务器应用加载的时候,让一个类中的方法通过读取配置文件,把这些对象创建出来并存起来。在接下来的使用的时候,直接拿过来用就好了。那么,这个读取配置文件,创建和获取三层对象的类就是工厂。
什么是控制反转
- 对象存哪去
- 分析:由于我们是很多对象,肯定要找个集合来存。这时候有 Map 和 List 供选择。 到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。
- 答案是: 在应用加载时,创建一个 Map,用于存放三层对象。 我们把这个 map 称之为容器。
- 什么是工厂
- 工厂就是负责给我们从容器中获取指定对象的类。这时候我们获取对象的方式发生了改变。
- 原来:
- 我们在获取对象时,都是采用 new 的方式。是主动的。
- 我们在获取对象时,都是采用 new 的方式。是主动的。
- 现在:
- 我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的。
- 我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的。
- 这种被动接收的方式获取对象的思想就是控制反转,它是 spring 框架的核心之一。
IoC的作用
- 消减计算机程序的耦合(解除我们代码中的依赖关系)
使用spring的IOC解决程序耦合
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">
<!--把对象的创建交给spring管理-->
<bean id="accountService" class="com.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl"></bean>
</beans>
- 主方法中
public class Client {
public static void main(String[] args) {
//========Application==========
//1.获取核心容器对象 单例对象适用(采用此接口)
//① ClassPathXmlApplicationContext
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
/* ② FileSystemXmlApplicationContext
ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\86133\\Desktop\\bean.xml");*/
//2.根据id获取Bean对象 多例对象适用
IAccountService as = (IAccountService) ac.getBean("accountService");
IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
System.out.println(as);
System.out.println(adao);
//as.saveAccount();
//========BeanFactory的使用=========
/*Resource resoure = new ClassPathResource("bean.xml");
BeanFactory factory = new XmlBeanFactory(resoure);
IAccountService as = (IAccountService) factory.getBean("accountService");
System.out.println(as);*/
}
}
ApplicationContext的是三个常用实现类
- ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下。不再的话,加载不了。
- FileSystemXmlApplicationContext:它可以加载磁盘任意路径下的配置文件(必须要有访问权限)
- AnnotationConfigApplicationContext:它是用于解读注解创建容器的
核心容器的两个接口引发的问题:
- ApplicationContext(单例适用):
- 它在构建核心容器时,创建对象采取的策略是采用立即加载,也就是说,只要已读取完配置文件马上就创建配置文件中配置的对象
- BeanFactory(多例适用):
- 它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式,也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象
IOC中bean标签和管理对象的细节
bean标签
- 作用:
- 用于配置对象让spring创建,默认情况下它待用的是类中的无参构造函数,如果没有无参构造函数则不能创建成功
- 属性:
- id:给对象再容器中提供一个唯一标识,用于获取对象
- class:指定类的全限定类名。用于反射创建对象。默认情况调用无参构造函数
- scope:指定对象的作用范围:
- singleton:默认值,单例的
- prototype:多例的
- request:web项目中,Spring创建一个Bean的对象,将对象存入到request域中
- session:web项目中,Spring创建一个Bean的对象,将对象存入到session域中
- global session(下图所示):web项目中,应用在Portlet环境,如果没有Portlet环境那么就相当于session
- ini-method:指定类中的初始化方法名称
- destory-method:指定类中销毁方法名称
bean的生命周期
- 单例对象:scope=“singleton” :一个应用只有一个对象的实例。它的作用范围就是整个引用。
- 生命周期:
- 对象出生:当应用加载,创建容器时,对象就被创建了。
- 对象活着:只要容器在,对象一直活着。
- 对象死亡:当应用卸载,销毁容器时,对象就被销毁了。
- 多例对象:scope=“prototype” 每次访问对象时,都会重新创建对象实例。
- 生命周期:
- 对象出生:当使用对象时,创建新的对象实例。
- 对象活着:只要对象在使用中,就一直活着。
- 对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。
实例化Bean的三种方式
- 使用默认无参构造函数
- 在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建
<bean id="accountService" class="com.service.impl.AccountServiceImpl"></bean>
- 使用普通工厂中的方法创建对象 (使用某个类中的方法创建对象,并存入spring容器)
- factory-bean属性:用于指定实例工厂bean的id
- factory-method属性:用于指定实例工厂中创建对象的方法
<bean id="instanceFactory" class="com.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
- 使用工厂中的静态方法创建对象 (使某个类中的静态方法创建对象,并存入spring容器中)
- id属性:指定bean的id,用于从容器中获取
- class属性:指定静态工厂的全限定类名
- factory-method属性:指定生产对象的静态方法
<bean id="accountService" class="com.factory.StaticFactory" factory-method="getAccountService"></bean>
spring的依赖注入
- 构造函数注入
- 使用的标签:constructor-arg
- 标签出现的位置:bean标签的内部
- 标签中的属性:
- type:用于指定要注入的数据的数据类型, 该数据类型也是构造函数中某个或某些参数的类型
- index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引的位置是从0开始
- name:用于指定给构造函数中指定名称的参数赋值(常用名称)
- value:用于提供基本类型和String类型的数据
- ref:用于指定其他的bean类型数据,它指的就是在spring的ioc核心容器中出现过的bean对象
- 优势:在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功
- 弊端:改变了bean对象的实例化方式,是我们在创建对象时,如果用不到这些数据,也必须提供
<bean id="accountService" class="com.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="test"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!--配置一个日期对象-->
<bean id="now" class="java.util.Date"></bean>
- set方法注入
- 涉及的标签:property
- 出现的位置:bean标签的内部
- 标签中的属性:
- name:用于注定注入时所调用的set方法的名称
- value:用于提供基本类型和String类型的数据
- ref:用于指定其他的ean类型数据,它指的就是在spring得Ioc核心容器中出现过得bean对象
- 优势:创建对象时没有明确得限制,可以直接使用默认构造函数
- 弊端:如果由某个成员必须优质,则获取对象时有可能set方法没有执行
<bean id="accountService2" class="com.service.impl.AccountServiceImpl2">
<property name="name" value="TEST"></property>
<property name="age" value="18"></property>
<property name="birthday" ref="now"></property>
</bean>
- 复杂类型得注入/集合类型得注入
- 用于给List结构集合注入得标签:list array set
- 用于给Map结构集合注入得标签:map props
- 结论:结构相同,标签可以互换
<bean id="accountService3" class="com.service.impl.AccountServiceImpl3">
<property name="myStrs">
<array>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</array>
</property>
<property name="myList">
<list>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</list>
</property>
<property name="mySet">
<set>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</set>
</property>
<property name="myMap">
<map>
<entry key="testA" value="aaa"></entry>
<entry key="testB">
<value>bbb</value>
</entry>
</map>
</property>
<property name="myProps">
<props>
<prop key="testC">ccc</prop>
</props>
</property>
</bean>
基于注解的IOC
常用注解
-
用于创建对象的
-
他们的作用就和在xml配置文件中编写一个<bean>标签实现的功能是一样的
-
常用注解:
- @Component
- 作用:把当前类对象存入Spring容器中
- 属性:value:用于指定bean的id,当我们不写时,它的默认值是当前类名,且首字母小写
- @Controller:一般用在表现层
- @Service:一般用在业务层
- @Repository:一般用在持久层
-
以上三个注解他们的作用和属性与Component是一模一样。他们三个是Spring框架为我们提供明确的三层的注解,使我们的三层对象更加清晰
-
-
用于注入数据的
- 他们的作用就和在xml配置文件中的标签中写一个标签的作用是一样的
- 常用注解
- @AutoWired
- 作用:自动按照类型注入,只要容器中有唯一的bean对象类型和要注入的变量类型匹配,就可以注 入成功,如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。 如果有Ioc容器中有多个类型匹配时,就找bean的id和变量名匹配的。
- 出现位置:可以是变量上,也可以是方法上
- 细节:在使用注解注入时,set方法不是必须的了
- @Qualifier:
- 作用:在按照类型注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用,但是在给方法参数注入时可以
- 属性:value:用于指定注入bean的id
- @Resource
- 作用:直接按照bean的id注入,它可以独立使用
- 属性:name:用于指定bean的id
- 以上三个注解都只能注入其他bean类型的数据。而基本类型和String类型无法使用上述注解实现。另外,集合类型的注入只能通过XML来实现
- @Value
- 作用:用于注入基本类型和String类型的数据
- 属性:value:用于指定数据的值,它可以使用Spring中的SpEL(也就是Spring的el表达式),SpEL的写法:${表达式}
-
用于改变作用范围的
- 他们的作用就和在bean标签中使用scope属性实现的功能是一样的
- 常用注解
- @Scope
- 作用:用于指定bean的作用范围
- 属性:value:指定范围的取值。常用取值:singleton prototype
-
和生命周期相关
- 他们的作用就和在bean标签中使用init-method和destroy-method的作用是一样的
- 常用注解
- @PreDestroy
- 作用:用于指定销毁方法
- @PostConstruct
- 作用:用于指定初始化方法
新注解
- @Configuration
- 作用:指定当前类是一个配置类
- 细节:当配置类作为AnnotationConfigApplicationContext对象创建参数时,该注释可以不写
- @ComponentScan
- 作用:用于通过注解指定spring在创建容器时要扫描的包
- 属性:value:它和basePackages的作用是一样的额,都是用于指定创建容器时要扫描的包。我们使用此注解就等同有在xml中配置了 <context:component-scan base-package=“com”></context:component-scan>
- @Bean
- 作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
- 属性:name:用于指定bean的Id,当不写时默认值是当前方法的名称
- 细节:当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的作用是一样的
- @import
- 作用:用于导入其他配置类
- 属性:
- value:用于指定其他配置类的字节码当我们使用Import的注解之后,有Import注解的类就是父配置类 ,而导入的都是子配置类
- @PropertySource
- 作用:用于指定properties文件的位置
- 属性:value:指定文件的名称和路径关键字:classpath,表示类路径下
整合Junit
spring整合junit的配置的步骤
- 导入spring整合Junit的jar(坐标)
- 导入junit提供的一个注解把原有的main方法替换了,替换成spring提供的@Runwith(SpringJUnit4ClassRunner.class)
- 告知spring的运行器。spring的ioc创建是基于xml还是注解的,并说明位置用,@ContextConfiguration,locations:指定xml文件的位置,加上classpath关键字,表示在类路径下,classes:配置类的字节码文件
- 当我们使用spring 5.x版本的时候,要求Junit的jar必须是4.12及以上
package com.test;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService accountService;
@Test
public void testFindAll(){
List<Account> accounts = accountService.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
@Test
public void testFindOne(){
Account account = accountService.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave(){
Account account = new Account();
account.setName("ddd");
account.setMoney(4000.0f);
accountService.saveAccount(account);
}
@Test
public void testUpdate(){
Account account = new Account();
account.setId(4);
account.setName("eee");
account.setMoney(4000.0f);
accountService.updateAccount(account);
}
@Test
public void testDelete(){
accountService.deleteAccount(4);
}
}
AOP相关概念
AOP概述
什么是AOP
- 全称是 Aspect Oriented Programming 即:面向切面编程
AOP的作用及优势
- 作用:在程序运行期间,不修改源码已有方法进行增强
- 优势:
- 减少重复代码
- 提高开发效率
- 维护方便
AOP的实现方式
- 使用动态代理技术
AOP的源码实现(通过动态代理)
动态代理的实现
- 字节码随用随创建,随用随加载
- 它与静态代理的区别也在于此,因为静态代理是字节码一上来就创建好,并完成加载
- 装饰者模式是静态代理的一种体现
/**
* 获取Service的代理对象
* @return
*/
public IAccountService getAccountService() {
return (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
/**
* 添加事务支持
*/
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue = null;
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
rtValue = method.invoke(accountService,args);
//3.提交事务
txManager.commit();
//4.返回结果
return rtValue;
}catch (Exception e){
txManager.rollback();
throw new RuntimeException(e);
}finally {
txManager.release();
}
}
}
);
}
动态代理的两种方式
- 基于接口的动态代理
/**
* 动态代理
* 特定:字节码随用随创建,随用随加载
* 作用:不修改源码的基础上对方法增强
* 分类:
* 基于接口的动态代理
* 基于子类的动态代理
* 基于接口的动态代理
* 涉及的类 Proxy
* 提供者:jdk官方
* 如何创建对象
* 使用Proxy类中的newProxyInstance方法
* 创建代理对象的要求
* 被代理类最少实现一个接口,如果没有则不能使用
* newProxyInstance方法的参数
* ClassLoader:类加载器
* 它是用于加载代理对象实现字节码的。和被代理对象使用相同的类加载器。固定写法
* Class[]:字节码数组
* 它是用于让代理对象和被代理对象由相同的方法。固定写法
* InvocationHandler:用于提供增强的代码
* 它是让我们写如何代理。我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的
* 此接口的实现类都是谁用谁写
*/
IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(Producer.class.getClassLoader(),
producer.getClass().getInterfaces(),
new InvocationHandler() {
/**
* 作用:执行被代理对象的任何接口方法都会经过该方法
* 方法参数的含义:
* @param proxy:代理对象的引用
* @param method:当前执行的方法
* @param args:当前执行方法的参数
* @return :和被代理对象方法有相同的返回值
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//提供增强的代码
Object returnValue = null;
//1.获取方法执行的参数
Float money = (Float) args[0];
//2.判断当前方法是不销售
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
}
);
- 基于子类的动态代理
/**
* 动态代理
* 特定:字节码随用随创建,随用随加载
* 作用:不修改源码的基础上对方法增强
* 分类:
* 基于接口的动态代理
* 基于子类的动态代理
* 基于子类的动态代理
* 涉及的类 Enhancer
* 提供者:第三方cglib库
* 如何创建对象
* 使用Enhancer类中的create方法
* 创建代理对象的要求
* 被代理类不能是最终类(final修饰)
*
* create方法的参数:
* Class:字节码
* 它是用于指定被代理对象的字节码
* Callback:用于提供增强的代码
* 它是让我们写如何代理。我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的
* 此接口的实现类都是谁用谁写
* 我们一般写的都是该接口的子接口实现类:MethodInterceptor
*/
Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
/**
* 执行对代理对象的任何方法都会经过该方法
* @param proxy
* @param method
* @param args
* 以上三个参数和基于接口的动态代理中的invoke方法的参数是一样的
* @param methodProxy:当前执行方法的代理对象
* @return
* @throws Throwable
*/
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//提供增强的代码
Object returnValue = null;
//1.获取方法执行的参数
Float money = (Float) args[0];
//2.判断当前方法是不销售
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
cglibProducer.saleProduct(10000f);
Spring中的AOP
Spring中AOP的细节
AOP的相关术语
- Joinpoint(连接点):
- 所谓连接点是指那些被拦截到的点。在spring中,这些点只得是方法,因为spring只支持方法类型的连接点
- Pointcut(切入点)
- 所谓的切入点是指我们要对哪些Joinpoint进行拦截的定义
- Advice(通知/增强)
- 所谓通知是指拦截到Joinpoint之后所要做的事情就是通知
- 通知类型:前置通知,后置通知,异常通知,最终通知,环绕通知
- Introduction(引介)
- Introduction引介是一种特殊的通知在不修改类代码的前提下,Introduction可以在运行期为类动态地添加一些方法或Field
- Target(目标对象)
- 代理的目标对象
- Weaving(织入)
- 是指把增强应用到目标对象来创建新的代理对象的过程
- spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
- Proxy(代理)
- 一个类AOP织入增强后,就产生一个结果代理类
- Aspect(切面)
- 是切面点和通知(引介)的结合
基于XML的AOP配置
- 导入坐标(jar包)
<packaging>jar</packaging>
<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>
- 创建spring的配置文件并导入约束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
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
- aop:config标签:表明开始AOP配置
- aop:aspect标签:表明配置切面
- id属性:是给切面提供一个唯一标识
- ref属性:是指定通知类bean的id
- 在aop:aspect标签内部使用对应标签来配置通知的类型
- aop:before:表示前置通知
- aop:after-returning:表示后置通知
- aop:after-throwing:表示异常通知
- aop:after:表示最终通知
- aop:around:表示环绕通知
-
环绕通知(独立使用的)
- 问题:当我们配置了环绕通知后,切入点方法没有执行,而通知方法执行了
- 分析:通过对比动态代理中环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有
- 解决:Spring框架为我们提供了一个接口:ProceedingJoinPoint.该接口有一个方法proceed,此方法就相当于明确调用切入点方法,该接口就可以作为环绕通知的方法参数。在程序执行时spring框架会为我们提供该接口的实现类供我们使用
- spring中的环绕通知:它是spring框架为我们提供的一个可以在代码中手动控制增强方法何时执行的方式
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs(); //得到方法执行所需的参数
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了-----前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了-----后置");
return rtValue;
}catch (Throwable t){
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了-----异常");
throw new RuntimeException(t);
}finally {
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了-----最终");
}
}
- 通知类型标签中的属性
- method属性:用于指定某个类中的哪个方法是前置通知
- pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中的哪些方法增强
- 切入点表达式的写法:execution(表达式)
- 表达式: 访问修饰符 返回值 包名.包名.包名…类名.方法名(参数列表)
- 标准表达式: public void com.service.impl.AccountServiceImpl.saveAccount()
- 访问修饰符可以省略: void com.service.impl.AccountServiceImpl.saveAccount()
- 返回值可以使用通配符,表示任意返回值:* com.service.impl.AccountServiceImpl.saveAccount()
- 包名可以使用通配符,表示任意包。但是有几级包,就需要写几个*.
* *.*.*.AccountServiceImpl.saveAccount()
包名可以使用…表示当前包及其子包: * *…AccountServiceImpl.saveAccount() - 类名和方法名都可以使用*来实现通配:
- 类名:* *…*.saveAccount()
- 方法名:* *…*.*()
- 参数列表
- 可以直接写数据类型
- 基本数据类型直接写名称
- 引用类型写包名.类名的方式 java.lang.String
- 可以使用通配符标识任意类型,但是必须有参数
- 可以使用…表示有无参数均可,有参数可以是任意类型
- 全通配写法: * *…*.*(…)
- 实际开发中切入点表示的通常写法
- 切到业务层实现类下的所有方法:* com.service.impl.*.*(…)
<!--配置Logger类-->
<bean id="logger" class="com.utils.logger"></bean>
<!--配置AOP-->
<aop:config>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知的类型,并且建立通知方法和切入点方法的关联-->
<aop:before method="printLog" pointcut="execution(* com.service.impl.*.*(..))"></aop:before>
</aop:aspect>
</aop:config>
基于注解的AOP
- 导入坐标(jar)
<packaging>jar</packaging>
<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>
- 导入约束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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
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"></context:component-scan>
- 配置通知类
package com.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 用于记录日志的工具类,它里面提供了公共代码
*/
@Component("logger")
@Aspect//表示当前类是一个切面类
public class logger {
@Pointcut("execution(* com.service.impl.*.*(..))")
private 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类中的afterThrowing方法开始记录日志了");
}
/**
* 最终通知
*/
@After("pt1()")
public void afterPrintLog(){
System.out.println("最终通知Logger类中的printLog方法开始记录日志了");
}
/**
* 环绕通知
*/
@Around("execution(* com.service.impl.AccountServiceImpl.saveAccount())")
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs(); //得到方法执行所需的参数
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了-----前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了-----后置");
return rtValue;
}catch (Throwable t){
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了-----异常");
throw new RuntimeException(t);
}finally {
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了-----最终");
}
}
}
- 不使用XML的配置方式
@Configuration
@ComponentScan(basePackages="com.itheima")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}
Spring中的JdbcTemplate
JdbcTemplate概述
- 他是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类
- 操作关系型数据库的:JdbcTemplate、HibernateTemplate
- 操作nosql数据库的:RedisTemplate
- 操作消息队列的:JmsTemplate
JdbcTemplate对象的创建
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
setDataSource(dataSource);
setLazyInit(lazyInit);
afterPropertiesSet();
}
除了默认构造函数之外,都需要提供一个数据源。既然有set方法,依据我们之前学过的依赖注入,我们可以
在配置文件中配置这些对象。
spring中配置数据源
- 环境搭建(导入坐标)
<?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.lee</groupId>
<artifactId>Spring_04JDBCTemplate</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>
<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>
</project>
- 编写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">
配置数据源
配置C3P0数据源
- 导入jar(坐标)
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
- 配置
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"/>
<property name="user" value="root"/>
<property name="password" value="123"/>
</bean>
配置DBCP数据源
- 导入jar(坐标)
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.2</version>
</dependency>
- 配置
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:// /spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
配置spring内置数据源
<!--配置DataSource-->
<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/spring?useUnicode=true&characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
JdbcTemplate的增删改查操作
在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">
<!--配置账户的持久层-->
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--<!–配置jdbcTemplate–>-->
<!--<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">-->
<!--<property name="dataSource" ref="dataSource"></property>-->
<!--</bean>-->
<!--配置DataSource-->
<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/spring?useUnicode=true&characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
</beans>
最基本使用
package com.jdbctemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
* jdbcTemplate的最基本用法
*/
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//2.执行操作
jt.execute("insert into account(name,money)values('eee',1000)");
}
}
保存操作
jt.update("insert into account(name,money) values(?,?)","ddd",100);
更新操作
jt.update("update account set name=?,money=? where id=?","fff",155,9);
删除操作
jt.update("DELETE FROM account where id=?",9);
查询所有操作
List<Account> accountList = jt.query("select * from account where money>?",new AccountRowMapper(),1000f);
List<Account> accountList = jt.query("select * from account where money>?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
for(Account account:accountList){
System.out.println(account);
}
/**
* 定义Account的封装策略
*/
class AccountRowMapper implements RowMapper<Account>{
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setMoney(resultSet.getFloat("money"));
return account;
}
}
查询一个操作
List<Account> accountList = jt.query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),1);
System.out.println(accountList.isEmpty()?"没有内容":accountList.get(0));
查询返回一行一列操作
Long count = jt.queryForObject("select count(*) from account where money>?", Long.class, 1000f);
System.out.println(count);
在Dao中使用JdbcTemplate
方式一:在Dao中定义jdbcTemplate
package com.dao.impl;
import com.dao.IAccountDao;
import com.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl2 implements IAccountDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
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);
}
public Account findAccountByName(String name) {
List<Account> accounts = jdbcTemplate.query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), name);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
方式二:让dao继承JdbcDaoSupportpackage
import com.dao.IAccountDao;
import com.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao{
public Account findAccountById(Integer id) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), id);
return accounts.isEmpty()?null:accounts.get(0);
}
public Account findAccountByName(String name) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), name);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
package com.dao.impl;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
/**
* 用于抽取Dao中的重复代码
*/
public class JdbcDaoSupport {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setDataSource(DataSource dataSource){
if(jdbcTemplate == null){
jdbcTemplate = createJdbcTemplate(dataSource);
}
}
private JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
-
注意:第一种方式在Dao类中定义JdbcTemplate的方式,适用于所有配置方式(xml和注解都可以)
-
第二种方式让Dao继承JdbcDaoSupport的方式,只能用于基于XML的方式,注解用不了
Spring中的事务控制
Spring中事务控制的API
PlatformTransactionManager
-
PlatformTransactionManager 接口提供事务操作的方法(三个具体操作)
- 获取事务状态的信息:TransactionStatus getTransaction(TransactionDefinition definition)
- 提交事务:void commit(TransactionStatus status)
- 回滚事务:void rollback(TransactionStatus status)
-
PlatformTransactionManager 接口的实现类
- 使用Spring JDBC或 iBatis 进行持久化数据时使用org.springframework.jdbc.datasource.DataSourceTransactionManager
- 使用Hibernate进行持久化数据时使用org.springframework.orm.hibernate5.HibernateTransactionManager
TransactionDefinition
-
事务信息的定义对象,里面有如下方法:
-
获取事务对象名称:String getName()
-
获取事务隔离级:int getIsoIationLevel()
-
获取事务传播行为:int getPRopagationBehavior()
-
获取事务超时时间:String getTimeout()
-
获取事务是否只读:String isReadOnly()
-
-
事务的隔离级别:反映事务提交并发访问时的处理态度
-
默认级别,归属下列某一种:ISOLATION_DEFAULT
-
可以读取未提交数据:ISOLATION_READ_UNCOMMITTED
-
只能读取已提交数据,解决脏读问题(Oracle默认级别):ISOLATION_READ_COMMITTED
-
是否读取其他事务提交修改后的数据,解决不可重复读问题(MySQL默认级别):ISOLATION_REPEATABLE_READ
-
是否读取其他事务提交添加后的数据,解决幻影读问题:ISOLATION_SERIALIZABLE
-
-
事务的传播行为
- REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
- SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
- MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
- REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
- NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
- NEVER:以非事务方式运行,如果当前存在事务,抛出异常
- NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作。
-
超时时间
- 默认值时-1,没有超时现在。如果有,以秒为单位进行设置
-
是否是只读事务
- 建议查询时设置为只读
TransactionStatus:此接口提供的事务具体的运行状态
- 具体的操作
-
刷新事务:void flush()
-
获取是否存在存储点:boolean hasSavepoint()
-
获取事务是否完成:boolean isCompleted()
-
获取事务是否为新的事务:boolean isNewTransaction()
-
获取事务是否回滚:boolean isRollbackOnly()
-
设置事务回滚:void setRollbackOnly()
-
基于XML的声明式事务控制
环境搭建
- 导入jar(坐标)
<?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.lee</groupId>
<artifactId>Spring_04Tx_xml</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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</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>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>
<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>
</project>
- 导入约束
<?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">
- 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.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置账户的业务层-->
<bean id="accountService" class="com.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置DataSource-->
<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/spring?useUnicode=true&characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
<!--spring中基于XML的声明式事务控制配置步骤
1.配置事务管理器
2.配置事务通知
此时我们需要导入事务的约束 tx名称空间约束,同时也需要aop的
id属性:给事务通知起一个唯一标识
transaction-manager:个体事务通知提供一个事务管理器引用
3.配置AOP中的通用切入点表达式
4.建立事务通知和切入点表达式的对应关系
5.配置事务的属性
是在事务的通知tx:advice标签的内部配置
-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></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="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置aop-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.service.impl.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
基于注解的配置方式
环境搭建
- 导入约束
<?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"></context:component-scan>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置DataSource-->
<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/spring?useUnicode=true&characterEncoding=utf8"></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="dataSource"></property>
</bean>
<!--开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
- 配置类
package com.service.impl;
import com.dao.IAccountDao;
import com.domain.Account;
import com.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* 事务控制应该都是在业务层
*/
@Service
@Transactional(propagation = Propagation.REQUIRED,readOnly = true)
public class AccountServiceImpl implements IAccountService{
@Autowired
private IAccountDao accountDao;
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer开始执行");
//①.根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//②.根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//③.转出账户减钱
source.setMoney(source.getMoney()-money);
//④.转入账户加钱
target.setMoney(target.getMoney()+money);
//⑤.更新转出账户
accountDao.updateAccount(source);
int i = 1/0;
//⑥.更新转入账户
accountDao.updateAccount(target);
}
}