前言
接触到Spring Aop 这块内容,AOP在Spring 中的典型应用就是事务管理,相对于编程式事务来说,声明式事务将事务管理代理从业务代码中分离出来,使业务代理不受污染,是Spring倡导的非侵入式的开发方式。
正文
一、Spring事务概述
Spring封装了事务管理代码,核心对象是platformTransactionManager对象,它实现了PlatformTransactionManager接口,来提供事务管理功能。
1、打开事务
2、提交事务
3、回滚事务
二、Spring管理事务的属性介绍
事务的隔离级别(isolation):解决事务的并发问题
- 1读未提交
- 2读已提交
- 4可重复读
- 8串行化
是否只读(read-only)
- true -只读,false-可操作性
事务的传播行为(propagation)(指在业务方法之间平行调用时,事务该如何处理)
- 最常用的是 Propagation.REQUIRED (支持当前事务,如果不存在,就新建一个(默认))
三、Demo
1、引入AOP 开发的包,导入约束(beans、context、aop、tx)
spring-aop.jar
spring-aspects.jar
aopalliance.jar
aspectJweaver.jar
2、创建目标类(实现转账业务:A向B转钱)
//转账接口类
package cn.itcast.service;
public interface AccountService {
//转账方法
void transfer(Integer from,Integer to,Double money);
}
/***********************************************/
//转账实现类
public class AccountServiceImpl implements AccountService {
private AccountDao ad;
public void setAd(AccountDao ad) {
this.ad = ad;
}
@Override
//转账方法
public void transfer(Integer from, Integer to, Double money) {
//减钱
ad.decreaseMoney(from, money);
//人造异常
//int i = 1/0;
//加钱
ad.increaseMoney(to, money);
}
}
3、配置事务管理器(applicationContext.xml)
<!-- 事务核心管理器,封装了所有事务操作,依赖于连接池 -->
<bean name = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref = "datasource"></property>
</bean>
4、配置事务的通知类
<!-- 配置事务通知,以方法为单位进行配置,指定什么方法应用什么事务属性
isolation:隔离级别
propagation:传播行为
read-only:是否只读 -->
<tx:advice id = "txAdvice" transaction-manager = "transactionManager">
<tx:attributes>
<tx:method name = "transfer" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "false"/>
</tx:attributes>
</tx:advice>
5、配置AOP事务(配置织入)
<!-- 配置织入 -->
<aop:config>
<aop:pointcut expression = "execution( * cn.itcast.service.*Impl.*(..))" id = "txPc"/>
<!-- 配置切面,通知+切入点 -->
<aop:advisor advice-ref = "txAdvice" pointcut-ref = "txPc"/>
</aop:config>
6、测试及结果
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name = "accountService")
private AccountService as;
@Test
//id为1的用户向id为2的用户转了100块钱
public void fun1(){
as.transfer(1, 2, 100d);
}
}
结果:当没有异常代码时,A转户少了100元钱,B账户多了100元钱;
当产生异常时,A和B账户的钱都没有变化(产生异常,事务回滚)。
总结
xml 方式完成声明式事务管理先介绍到这里,感谢阅读!