如何在Spring中获取事务信息,无论是声明式事务管理中的事务已提交还是回滚? [英] How do I get transaction info in Spring whether transaction is committed or rollback in a declarative transaction management?

查看:470
本文介绍了如何在Spring中获取事务信息,无论是声明式事务管理中的事务已提交还是回滚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下Spring声明式事务:

I use following declarative Spring transaction:

<!-- Declare a transaction manager-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />  
<!-- enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="transactionManager" mode="proxy" proxy-target-class="true"/>

这是DAO:

@Repository
@Transactional(readOnly = true, propagation=Propagation.REQUIRES_NEW )
@Scope("prototype")
public class Xdao{

    public Object getValues(){
        .....
    }
}


@Service
@Scope("prototype")
public class Xservice{
private Xdao xdao;

    public Object getx(){
        xdao.getValues();//here I want to know whether the transaction started  is             
        //committed or rollback by aop. Is it possible somehow? I don't want to include that code 
        //in any service or dao layer. 
        .........
    }

    @Autowired
    public void setXdao(Xdao xdao){
        this.xdao=xdao;
    }
}

我想了解交易状态,即交易已提交或回滚.我需要它来记录日志.

I want to know about transaction status i.e transaction is committed or rolled back. I need it for logging.

推荐答案

如果事务在范围内,则可以从TransactionAspectSupport.currentTransactionStatus()获取TransactionStatus.例如:

If transaction is in scope you can get TransactionStatus from TransactionAspectSupport.currentTransactionStatus(). For example:

if (TransactionSynchronizationManager.isActualTransactionActive()) {
   TransactionStatus status = TransactionAspectSupport.currentTransactionStatus();
   ...
}

但这在交易完成后将不起作用.

But this will not work after transaction is completed.

您可以添加TransactionSynchronization并实现afterCompletion(int status)来记录状态或将其存储在ThreadLocal变量中以供以后使用.

You could add a TransactionSynchronization and implement afterCompletion(int status) to log the status or store it in a ThreadLocal variable for later usage.

public class LogTransactionSynchronization extends TransactionSynchronizationAdapter {
   @Override
   public afterCompletion(int status) {
      // log the status or store it for later usage
   }
}

这篇关于如何在Spring中获取事务信息,无论是声明式事务管理中的事务已提交还是回滚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆