spring 本類中方法呼叫另外一個方法事務不生效
阿新 • • 發佈:2019-04-25
1、在spring配置檔案中新增 <aop:aspectj-autoproxy expose-proxy="true"/> 宣告自動代理
2、AopContext.currentProxy()來獲取代理類
3、使用代理類proxy進行代理呼叫內部聲明瞭事務的方法
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by ysma on 2019/4/25.
*/
@Service
public class TransactionService {
public void methodA(){
boolean flag = true;
if(flag){
TransactionService proxy = (TransactionService)AopContext.currentProxy();
proxy.methodB();//生效
} else {
methodB();//事務不生效
}
}
@Transactional
public void methodB(){
//my transaction
}
}