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
}
});
}
}
}