Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

使用 Spring AOP 記錄日誌

基本思路

Spring AOP 可以在方法執行前後插入日誌邏輯。常見做法是定義切面類,配置切點,再把日誌方法綁定到前置或後置通知。

普通類攔截

public class MyLog {
public void before() {
System.out.println("方法執行前");
}
public void after() {
System.out.println("方法執行後");
}
}

配置示例

<bean id="testLog" class="chen.hui.log.MyLog"></bean>
<aop:config>
<aop:aspect id="b" ref="testLog">
<aop:pointcut id="log" expression="execution(* chen.hui.log.*.*(..))"/>
<aop:before pointcut-ref="log" method="before"/>
<aop:after pointcut-ref="log" method="after"/>
</aop:aspect>
</aop:config>

Action 攔截

若需要記錄 Action 調用信息,可以在通知方法中接收 JoinPoint。通過 getArgs 等方法可以取得調用參數,再按需記錄請求路徑、方法名與業務參數。

注意事項

普通類可以針對單個類配置切點;Action 場景下,切點表達式通常需要覆蓋整個包,否則可能出現攔截失敗或配置錯誤。

Copyright © Linux教程網 All Rights Reserved