几年前记得整理过,@Transacitonal注解的方法被另外一个方法调用的时候,事务是不生效的,其原因在于spring @Transactional是通过动态代理实现的,可以参见https://blog.csdn.net/yangquanwa/article/details/88578357

如果大量代码已经这么写了,这个时候抽取出去不现实,怎么办呢?

答案就是在<aop:aspectj-autoproxy />中设置expose-proxy属性为true暴露代理。如下:

<aop:aspectj-autoproxy expose-proxy=“true”> ,然后使用AopContext.currentProxy()获取当前代理,将this.b()改为((UserService)AopContext.currentProxy()).b(),这样就生效了。完整的例子如下:

public interface UserService{
    public void a();
    public void a();
}

public class UserServiceImpl implements UserService{
    @Transactional(propagation = Propagation.REQUIRED)
    public void a(){
        this.b();
    }
    @Transactional(propagation = Propagation.REQUIRED_NEW)
    public void b(){
        System.out.println("b has been called");
    }
}

 对应的spring boot注解为@EnableAspectJAutoProxy(exposeProxy=true)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-05
  • 2022-01-22
猜你喜欢
  • 2022-12-23
  • 2021-07-30
  • 2021-09-28
  • 2021-05-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案