以银行转账为例(本文只作为自己学习spring的备忘录,只对自己负责)
转账的dao层接口
转账dao层接口实现类
业务逻辑接口实现类
- package com.slowly.springtrancation03;
- import org.springframework.transaction.TransactionStatus;
- import org.springframework.transaction.support.TransactionCallbackWithoutResult;
- import org.springframework.transaction.support.TransactionTemplate;
- public class accountServiceImp implements accountService {
- private accountDao accountDao;
- public void setAccountDao(accountDao accountDao) {
- this.accountDao = accountDao;
- }
-
- @Override
- public void transfer(String out, String in, Double money) {
- accountDao.outMoney(out, money);
- //int i = 1/0;
- accountDao.inMoney(in, money);
- }
-
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:context="http://www.springframework.org/schema/context" 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/tx/spring-tx.xsd"> <!-- 引入外部的文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置c3p0的连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> </bean> <!-- 配置业务层 --> <bean id="accountService" class="com.slowly.springtrancation03.accountServiceImp"> <property name="accountDao" ref="accountDao"></property> </bean> <!-- 配置dao层 --> <bean id="accountDao" class="com.slowly.springtrancation03.accountDaoImp"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 事务管理配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务的通知,(事务的增强) --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="transfer" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 配置切面 --> <aop:config> <!-- 配置切入点 --> <aop:pointcut expression="execution(* com.slowly.springtrancation03.accountService+.*(..))" id="pointcut01"/> <!-- 配置切面 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut01"/> </aop:config> </beans>
测试