import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
//本类实现了一个事务,本地提交成功后再执行其他的事情
public class TestTransaction
{
@Autowired
TransactionTemplate transactionTemplate;
public void testTransaction(Objectobject)
{
Object result = transactionTemplate.execute(new TransactionCallback<Object>()
{
@Override
public Object doInTransaction(TransactionStatusstatus)
{
return doTransaction();
}
});
}
private Object doTransaction()
{
//do something
//注意如下代码需要在数据库提交前注册到事务中
registTransactionSynchronizationManager();
//operate DB
return new Object();
}
private void registTransactionSynchronizationManager()
{
if (TransactionSynchronizationManager.isSynchronizationActive())
{
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
{
//事物提交完毕后执行
@Override
public void afterCommit()
{
//doSomething
}
});
}
}
}