基于TransactionProxyFactoryBean的方式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: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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/aop/spring-tx.xsd">
<!-- 引入外部的属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置业务层类 -->
<bean id="accountService" class ="demo2.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!-- 配置DAO的类 -->
<bean id ="accountDao" class = "demo2.AccountDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置业务层的代理 -->
<bean id="accountServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<!-- 配置一个目标对象 -->
<property name="target" ref="accountService"/>
<!-- 注入事务管理器 -->
<property name="transactionManager" ref="transactionManager"/>
<!-- 注入事务的一些属性 -->
<property name="transactionAttributes" >
<props>
<!-- 格式:
<prop key="方法">参数</prop>
* PROPAGATION :事务的传播行为
* ISOLATION :事务的隔离级别
* readOnly :只读.(不可以进行修改、插入、删除)
* -Exception :发生哪些异常回滚事务
* +Exception :发生哪些异常事务不回滚
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
-->
<!-- <prop key="transfer">PROPAGATION_REQUIRED</prop> -->
<prop key="transfer">PROPAGATION_REQUIRED,+java.lang.ArithmeticException</prop>
</props>
</property>
</bean>
</beans>
JAVA测试类
public class SpringDemo2 {
/**
* 注入代理类:因为代理类进行增强的操作
*/
// @Resource(name="accountService")
@Resource(name="accountServiceProxy")
private AccountService accountService;
@Test
public void demo(){
accountService.transfer("aaa", "bbb", 200d);
}
}
调用业务层实现类的方法
/**
*
* @param out :转出的账号
* @param in :转入的账号
* @param money :转账金额
*/
@Override
public void transfer(String out, String in, Double money) {
// TODO Auto-generated method stub
accountDao.outMoney(out, money);
int d = 1/0;
accountDao.inMoney(in, money);
}