首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring AOP 實戰:構建強大的日誌記錄功能

     編輯:Java 相關知識

需求背景

專案需為所有增刪改操作記錄詳細日誌:操作者、執行方法、IP、方法參數。以往在 Filter 中實現,現要求改用 Spring AOP,以便無縫整合現有系統並靈活配置切點。

實作步驟

1. 啟用 @AspectJ 支援

在 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>

2. 配置切面 Bean

定義處理日誌的普通 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>

3. 定義切面類與切點

使用 @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() {}
}

4. 編寫通知邏輯

使用 @AfterReturning 在目標方法正常返回後記錄日誌,透過 JoinPoint 獲取方法名、參數、類路徑等:

@AfterReturning("insertPointcut()")
public void insertLogInfo(JoinPoint joinPoint) throws Exception {
    // 1. 從 JoinPoint 取得方法簽名、參數陣列
    // 2. 結合 sessionValue、userIpAddress、當前時間等資訊
    // 3. 組裝日誌物件並持久化(略)
}

關鍵點總結

  • 無侵入性:業務代碼零修改,透過配置即可織入日誌功能。
  • 靈活擴展:切點運算式可精準控制攔截範圍;通知中可任意擴展邏輯。
  • 參數獲取:JoinPoint 提供豐富上下文資訊,滿足詳細審計需求。

完整源碼包含 Spring 配置與切面類,可直接應用於專案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved