如何跟踪 Spring 交易结果?

prdp8dxp  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(284)

你可以想象我有一些服务,说是金钱服务。还假设我有一个方法,执行实际的传输(我知道,这是一个非常平凡的例子)。如果交易成功,我必须返回true,否则返回false。所以,这里有一个我实际上没有掌握的想法——如何在spring框架中跟踪事务的结果(甚至可能只是为了简单的日志记录目的)下面给出了我的传输方法的示例。谢谢你的帮助。

@Transactional
    public boolean transferMoneyFromOneAccountToAnother(MoneyTransferForm moneyTransferForm) {
        final UserBankAccount sourceBankAccount = bankAccountRepository.findBankAccountByIdentifier(
                moneyTransferForm.getSourceAccountIdentifier()
        );
        final UserBankAccount targetBankAccount = bankAccountRepository.findBankAccountByIdentifier(
                moneyTransferForm.getTargetAccountIdentifier()
        );
        subtractMoneyFromSourceAccount(moneyTransferForm, sourceBankAccount);
        appendMoneyToTargetAccount(moneyTransferForm, targetBankAccount);
        bankAccountRepository.updateUserBankAccount(sourceBankAccount);
        bankAccountRepository.updateUserBankAccount(targetBankAccount);
    }
yfwxisqw

yfwxisqw1#

我可以想出两种方法:
您可以简单地用try/catch块括起您的方法调用,如果没有异常,那么您的事务已成功提交。

try{
     transferMoneyFromOneAccountToAnother()

     logger.info("Transacton Done Successfully");

 }catch(Exception ex){
      //transaction failed
      logger.error("Transaction failed")
 }

您可以使用@transactionaleventlistener注解一个方法,并监听您的自定义事件。您可以查看这些链接以了解其工作原理:https://www.baeldung.com/spring-events
@@transactional test中未调用transactionaleventlistener注解的方法

相关问题