使用ssm过程中,遇到了service自调的问题,于是研究了this与AOP代理两种方法。
测试类:
public interface IService {
void a();
void b();
}
@Service("service")
public class ServiceImpl implements IService{
@Override
@Transactional(propagation=Propagation.REQUIRED)
public void a() {
// this.b();
((IService) AopContext.currentProxy()).b();
}
@Override
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void b() { }
}
this.b()的方式:
如果 a 方法使用 this.b( ) 的方式调用方法,b 事务是不会增强的,Spring 文档中说过,只有外部调动才会增强, this 指的是当前对象,而不是 proxy 对象,所以事务不会增强。这时候 b 方法上的 @Transactional(propagation = Propagation.REQUIRES_NEW) 不起作用,也就是说这时候 b 方法与 a 方法的事务定义是一样的,这一点可以从日志中看出:
Returning cached instance of singleton bean 'service'
Adding transactional method 'ServiceImpl.a' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
Returning cached instance of singleton bean 'transactionManager'
//创建新事务(a事务)
Creating new transaction with name [com.llangzh.services.impls.ServiceImpl.a]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
incremented pending_acquires: 1
incremented pending_acquires: 2
incremented pending_acquires: 3