spring入门(四)转账日志(事务管理案例)

一、转账业务追加日志分析

实现任意两个账户间转账操作,并对每次转账操作在数据库进行留痕

即:A账户减钱,B账户加钱,数据库记录日志

无论转账操作是否成功,均进行转账操作的日志留痕

二、事务传播行为

事务传播行为:事务协调员对事务管理员所携带事务的处理态度

添加日志是一个新的事务;

事务传播行为:

三、转账日志案例

实现步骤:

第一步、在AccountServiceImpl中调用logService中添加日志的方法, 添加日志是一个新的事务。

java 复制代码
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Autowired
    private LogService logService;

    public void transfer(String out,String in ,Double money) {
        try{
            accountDao.outMoney(out,money);
            int i = 1/0;
            accountDao.inMoney(in,money);
        }finally {
            logService.log(out,in,money);
        }
    }
}

第二步、在LogService的log()方法上设置事务的传播行为

java 复制代码
public interface LogService {
    //propagation设置事务属性:传播行为设置为当前操作需要新事务
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void log(String out, String in, Double money);
}

第三步、运行测试类,查看结果

java 复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer() throws IOException {
        accountService.transfer("Tom","Jerry",50D);
    }
}

实现成功。

相关推荐
于先生吖6 分钟前
Java+SpringBoot 无人健身房物联网系统完整源码实现
java·spring boot·物联网
johnrui25 分钟前
SpringBoot-JdbcTemplate
java·spring boot·后端
码云社区27 分钟前
JAVA二手车交易二手车市场系统源码支持微信小程序+微信公众号+H5+APP
java·开发语言·微信小程序·二手交易·闲置回收
crescent_悦28 分钟前
C++:The Largest Generation
java·开发语言·c++
indexsunny40 分钟前
互联网大厂Java面试实战:从Spring Boot到微服务的技术问答解析
java·spring boot·redis·微服务·消息队列·电商
希望永不加班2 小时前
SpringBoot 过滤器(Filter)与请求链路梳理
java·spring boot·后端·spring
Lyyaoo.2 小时前
【JAVA基础面经】抽象类/方法与接口
java·开发语言
0xDevNull2 小时前
Java实现Redis延迟队列:从原理到高可用架构
java·开发语言·后端
于先生吖2 小时前
无人共享健身房 Java 后端源码 + 多端对接完整方案
java·开发语言
恼书:-(空寄2 小时前
Spring 事务失效的 8 大场景 + 原因 + 解决方案
java·后端·spring