幾年前記得整理過,@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)