Spring AOP方法內部調用不生效的解決方案
問題描述
最近有個需求,統(tǒng)計某個方法的調用次數,開始使用 Spring AOP 實現(xiàn),后來發(fā)現(xiàn)當方法被內部調用時,切面邏輯將不會生效,直接上樣例:
定義接口,包含方法 A,方法 B
public interface ISon {
void A();
void B();
}
定義接口實現(xiàn),方法 B 調用方法 A
@Service
public class Son implements ISon {
@Override
public void A() {
System.out.println("method A");
}
@Override
public void B() {
System.out.println("method B");
A();
}
}
切點定義,對方法 A 進行增強
@Aspect
@Component
public class AspectDemo {
@Pointcut(value = "execution(* com.example.transactiondemo.aop.ISon.A(..))")
public void pointCut(){
}
@Before("pointCut()")
public void before(JoinPoint joinPoint){
System.out.println("before ");
}
@After("pointCut()")
public void after(){
System.out.println("after ");
}
}
測試
@Autowired
private ISon iSon;
@Test
public void test11(){
iSon.A();
System.out.println("-----------");
iSon.B();
}
打印輸出
before
method A
after
-----------
method B
method A
可以發(fā)現(xiàn),如果直接使用 實例調用 A,會進行增強;但是如果是方法 B 調用,A 的增強邏輯將失效。
失效原因
方法 A 被調用,是基于 AOP 生成的 代理對象 進行的調用;方法 B 調用方法 A ,是 this 目標對象 直接調用,并不是代理對象進行調用

解決方案
回到最開始的需求,如何通過切面的方式獲取某一個方法的調用次數? 包括方法自調用
使用 AopContext.currentProxy()
切面開啟注解
@EnableAspectJAutoProxy(exposeProxy = true,proxyTargetClass = true)
方法 B 不直接調用 A
@Override
public void B() {
System.out.println("method B");
((Son) AopContext.currentProxy()).A();
}
先獲取上下文的 Bean 再調用
@Autowired private ApplicationContext applicationContext; ((Son) applicationContext.getBean(Son.class)).A();
以上就是Spring AOP方法內部調用不生效的解決方案的詳細內容,更多關于Spring AOP方法調用不生效的資料請關注腳本之家其它相關文章!
相關文章
java final 和instanceof 關鍵字的區(qū)別
這篇文章介紹了java final 和instanceof 關鍵字的區(qū)別,有需要的朋友可以參考一下2013-09-09
Spring Security 實現(xiàn)短信驗證碼登錄功能
這篇文章主要介紹了Spring Security 實現(xiàn)短信驗證碼登錄功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
Java OpenCV4.0.0實現(xiàn)實時人臉識別
這篇文章主要為大家詳細介紹了Java OpenCV4.0.0實現(xiàn)實時人臉識別,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
Java中的 BigDecimal 和 String 的相互轉換問題
這篇文章主要介紹了Java中的 BigDecimal 和 String 的相互轉換問題,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05

