1. Spring Aop 原理
Spring Aop 通過動態代理創建代理對象,在調用代理對象方法前后做增強。
2. Transactional
, Async
注解失效?
當在動態代理方法中調用當前實例的 Transactional
或 Async
標記的方法時,注解不會生效;
原因:在此條件下調用注解標記的方法相當於調用實例本身的方法 this.func()
,此時不會通過 Spring Aop 的增強,所以注解不生效
3. 注解失效的處理方式
- 配置
<aop:aspectj-autoproxy expose-proxy="true" />
暴露代理對象,Spring Boot 中可使用@EnableAspectJAutoProxy(exposeProxy=true)
注解 - 將方法中的
this.func()
調用修改為以下形式
// 從AppContext中獲取當前代理對象(ThreadLocal)
Object proxy = AppContext.currentProxy;
// 調用代理方法
proxy.func();