專案需為所有增刪改操作記錄詳細日誌:操作者、執行方法、IP、方法參數。以往在 Filter 中實現,現要求改用 Spring AOP,以便無縫整合現有系統並靈活配置切點。
在 Spring 配置檔加入命名空間與自動代理標籤:
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="https://www.springframework.org/schema/aop"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-2.0.xsd
https://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- 支援 @AspectJ 註解 -->
<aop:aspectj-autoproxy />
</beans>
定義處理日誌的普通 Bean,並注入需記錄的物件屬性映射:
<bean id="logAspect" class="com.hs.dolphin.sys.LogAspect">
<property name="obj_method">
<map>
<entry key="default">
<map>
<entry key="getId"><value>id</value></entry>
</map>
</entry>
<entry key="com.hs.dolphin.domain.User">
<map>
<entry key="getId"><value>id</value></entry>
<entry key="getUserName"><value>userName</value></entry>
</map>
</entry>
</map>
</property>
</bean>
使用 @Aspect 標記類,以 @Pointcut 定義匹配 Service 層增刪改方法:
@Aspect
public class LogAspect {
private UserSession sessionValue; // 當前操作員資訊
private String userIpAddress; // 當前操作員 IP
@Pointcut("execution(* *.*.*.service..*.insert*(..)) || " +
"execution(* *.*.*.service..*.update*(..)) || " +
"execution(* *.*.*.service..*.remove*(..)) || " +
"execution(* *.*.*.service..*.delete*(..))")
public void insertPointcut() {}
}
使用 @AfterReturning 在目標方法正常返回後記錄日誌,透過 JoinPoint 獲取方法名、參數、類路徑等:
@AfterReturning("insertPointcut()")
public void insertLogInfo(JoinPoint joinPoint) throws Exception {
// 1. 從 JoinPoint 取得方法簽名、參數陣列
// 2. 結合 sessionValue、userIpAddress、當前時間等資訊
// 3. 組裝日誌物件並持久化(略)
}
JoinPoint 提供豐富上下文資訊,滿足詳細審計需求。完整源碼包含 Spring 配置與切面類,可直接應用於專案。