声明式事务的管理:(自动代理,基于切面),这种方式需要重点掌握。
首先,预备工作是将项目恢复到最原始版本,详见环境搭建。
第一步:导入相应的jar包。aspectJ包(两个,详见aspectJ部分)
第二步:引入相应的约束 aop约束、tx约束
<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"
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/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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
第三步:注册事务管理器
<!-- 事务管理器 -->
<bean id="transactionmanager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
第四步:配置增强、切面、切点
<!-- 定义一个增强 -->
<tx:advice id="txAdvice" transaction-manager="transactionmanager">
<!-- 增强事务的属性的配置 -->
<!-- isolation:事务的隔离级别
propagation:事务的传播行为
read-only:false,不是只读
timeout:-1不过期
no-rollback-for:发生哪些异常不回滚
rollback-for:发生哪些异常回滚
-->
<tx:attributes>
<tx:method name="transfer" ></tx:method>
</tx:attributes>
</tx:advice>
<!-- aop配置定义切面 和切点的信息-->
<aop:config>
<!-- 定义切点:哪些类的哪些方法应用增强 -->
<aop:pointcut expression="execution(* com.js.demo3.AccountService+.*(..))" id="mypointcut"/>
<!-- 定义切面 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut"/>
</aop:config>
第五步:编写测试。
package com.js.demo3;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.js.demo3.AccountService;
/**
* 声明式事务的使用:基于切面
* @author jiangshuai
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext3.xml")
public class Test2 {
@Autowired
@Qualifier("accountService")
private AccountService accountService;
@Test
public void demo(){
//完成转账
accountService.transfer("aaa", "bbb", 100d);
}
}
运行测试,事务运行正常。
异常情况下,事务回滚的测试:
修改类AccountServiceImpl:
package com.js.demo3;
public class AccountServiceImpl implements AccountService{
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
/**
* 转账的方法
* @param from:从哪转出
* @param to:转入目标
* @param money:转账金额
*/
public void transfer(String from, String to,double money) {
accountDao.out(from, money);
int i = 4/0;
accountDao.in(to, money);
}
}
运行测试,表格金额没有改变,说明回滚测试成功。