spring 事务Propagation.REQUIRES_NEW 不起作用的原因
接着上一篇遗留的问题
@Transactional
public String updateAccountTest(AccountTest accountTest) throws BusinessException {
String strResult = "true";
try {
AccountMessage accountMessage = new AccountMessage();
accountMessage.setMessage("修改用户" + accountTest.getName() + "金额" + accountTest.getMoney());
this.updateAccountRequiresNew(accountTest);
// 如果updateAccountRequiresNew这个方法在本类定义,this.updateAccountRequiresNew(accountTest),结果又会是怎么样呢
accountMessageBusinessImpl.insertAccountMessageRequired(accountMessage);
} catch (BusinessException e) {
logger.error("类:AccountTestServiceImpl;方法:updateAccountTest;错误信息:" + e);
strResult = "false";
throw e;
} catch (RuntimeException e) {
throw e;
}
return strResult;
}
@Transactional(propagation=Propagation.REQUIRES_NEW)
public String updateAccountRequiresNew(AccountTest accountTest) throws BusinessException {
String strResult = "true";
try {
accountTestServiceImpl.updateObject("updateAccountTest", accountTest);
} catch (BusinessException e) {
logger.error("类:AccountTestServiceImpl;方法:updateAccountTest;错误信息:" + e);
strResult = "false";
throw e;
}
return strResult;
}
@Transactional(propagation=Propagation.REQUIRED)
public String insertAccountMessageRequired(AccountMessage accountMessage) throws BusinessException {
String strResult = "true";
try {
accountMessageServiceImpl.saveObject("insertAccountMessage", accountMessage);
int i=1/0;
} catch (BusinessException e) {
logger.error("类:AccountMessageServiceImpl;方法:insertAccountMessage;错误信息:" + e);
strResult = "false";
throw e;
}
return strResult;
}
@Transactional(propagation=Propagation.REQUIRED)
public String insertAccountMessageRequired(AccountMessage accountMessage) throws BusinessException {
String strResult = "true";
try {
accountMessageServiceImpl.saveObject("insertAccountMessage", accountMessage);
int i=1/0;
} catch (BusinessException e) {
logger.error("类:AccountMessageServiceImpl;方法:insertAccountMessage;错误信息:" + e);
strResult = "false";
throw e;
}
return strResult;
}
执行完测试代码后
发现数据库余额表并没有变更
目标对象的自我调用 Propagation.REQUIRES_NEW 不会起作用的 。
why?
我们首先调用的是AOP代理对象而不是目标对象,首先执行事务切面,事务切面内部通过TransactionInterceptor环绕增强进行事务的增强,即进入目标方法之前开启事务,退出目标方法时提交/回滚事务。
目标对象内部的自我调用将无法实施切面中的增强。
此处的this指向目标对象,因此调用this.b()将不会执行b事务切面,即不会执行事务增强,因此b方法的事务定义“@Transactional(propagation = Propagation.REQUIRES_NEW)”将不会实施
解决方法
1:不要做内部调用
2:从beanFactory中获取bean SpringContextUtil.getBean(…)