这里假设转账出现断电现象,假设在AccountServiceImpl.java中模拟断电
AccountServiceImpl.java
package com.gem.service;
import com.gem.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Calendar;
@Service
//表示该类中所有的方法具有声明式事务(设置声明式事务的传播)
@Transactional(propagation = Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {
@Autowired
AccountMapper accountMapper;
@Override
public void transfer(String fromAccountNo, String toAccountNo, Double money) {
//转出账户减出转账金额
accountMapper.updateAccount(fromAccountNo,money);
//出现异常情况...
doSomeBadThings();
//转入账户加上转账金额
accountMapper.updateAccount(toAccountNo,-money);
}
/**
* 模拟异常
*/
private void doSomeBadThings(){
Calendar calendar=Calendar.getInstance();
int second=calendar.get(Calendar.SECOND);
if(second<30){
throw new RuntimeException("服务器断电...");
}
}
}
则在秒表在30-60范围内是正确转账,在0-30范围内是不正常转账(左图为正常转账,右图为非正常转账)
这时要用声明式事务就可解决此问题
(1)先在applicationContext.xml中开启声明式事务
(2)然后配置事务管理器
(3)在AccountServiceImpl.java中加入注解
这样就可以解决此问题