声明式事务管理(基于Spring的AOP配置控制)
-基于TransactionProxyFactoryBean的方式.(很少使用)–见demo2包
需要为每个进行事务管理的类,配置一个TransactionProxyFactoryBean进行增强.
–基于TransactionProxyFactoryBean的方式
public class AccountServiceImpl implements AccountService {
// 注入转账的DAO
private AccountDao accountDao;
/**
* @param out
* :转出账号
* @param in
* :转入账号
* @param money
* :转账金额
*/
@Override
public void transfer(String out, String in, Double money) {
accountDao.outMoney(out, money);
// int i = 1/0;
accountDao.inMoney(in, money);
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
}
applicationContext2.xml
<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="com.zs.spring.demo2.AccountServiceImpl">
<property name="accountDao" ref="accountDao" />
</bean>
<!-- 配置DAO类(简化,会自动配置JdbcTemplate) -->
<bean id="accountDao" class="com.zs.spring.demo2.AccountDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- ==================================2.使用XML配置声明式的事务管理(原始方式)=============================================== -->
<!-- 配置事务管理器 -->
<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>
<!-- 注入事务的属性 -->
<property name="transactionAttributes">
<props>
<!--
prop的格式:
* PROPAGATION :事务的传播行为
* ISOTATION :事务的隔离级别
* readOnly :只读
* -EXCEPTION :发生哪些异常回滚事务
* +EXCEPTION :发生哪些异常不回滚事务
-->
<prop key="transfer">PROPAGATION_REQUIRED</prop>
<!-- <prop key="transfer">PROPAGATION_REQUIRED,readOnly</prop> -->
<!-- <prop key="transfer">PROPAGATION_REQUIRED,+java.lang.ArithmeticException</prop> -->
</props>
</property>
</bean>
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(“classpath:applicationContext2.xml”)
public class TransactionTest {
/**
* 一定要注入代理类:因为代理类进行增强的操作
*/
// @Resource(name=“accountService”)
@Resource(name = “accountServiceProxy”)
private AccountService accountService;
@Test
public void demo1() {
accountService.transfer("aaa", "bbb", 200d);
}
}