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

Spring MVC 利用 AOP 實現 Service 層操作日誌自動記錄

     編輯:Java 綜合教學

設計思路

利用 Spring AOP 切面,在 Service 方法執行後自動記錄操作日誌(用戶、IP、時間、調用方法),無侵入業務代碼。

實現步驟

  1. 定義日誌實體 SystemLog (id, opUser, opIp, opTime, function...)
  2. 編寫 Mapper/DAO 接口與映射文件 (CRUD)
  3. 封裝 Service 接口 ISystemLogService
  4. 編寫切面工具類 SystemLogUtils,實現 writeLog(JoinPoint jp)
  5. Spring 配置切面織入 (XML 或 @Aspect)

核心切面代碼

public class SystemLogUtils {
    private ISystemLogService service; // 注入

    public void setService(ISystemLogService service) { this.service = service; }

    @SuppressWarnings("rawtypes")
    public void writeLog(JoinPoint jp) {
        Object target = jp.getTarget();
        // 避免遞歸:若目標是日誌 Service 本身,直接返回
        if (target instanceof ISystemLogService) return;

        SystemLog log = new SystemLog();
        log.setOpUser(UserContext.getUser());      // 從 ThreadLocal 獲取當前用戶
        log.setOpIp(UserContext.getOpIp());        // 獲取請求 IP
        log.setOpTime(new Date());

        Class clazz = target.getClass();
        String methodName = jp.getSignature().getName();
        log.setFunction(clazz.getName() + "." + methodName); // 完整方法簽名

        service.save(log); // 持久化
    }
}

關鍵點解析

  • JoinPoint:切入點上下文,提供目標對象、方法簽名、參數等。
  • UserContext:自定義 ThreadLocal 封裝,綁定當前請求的用戶與 IP(需在 Filter/Interceptor 中設定)。
  • 遞歸保護:日誌寫入本身會調用 Service,必須排除自身切面,否則死循環。
  • 異步化建議:生產環境建議將 service.save() 放入異步執行器或消息隊列,避免阻塞主業務。

Spring XML 配置示例

<bean id="systemLogUtils" class="com.tab.crm.utils.SystemLogUtils">
  <property name="service" ref="systemLogService"/>
</bean>

<aop:config>
  <aop:aspect ref="systemLogUtils">
    <aop:pointcut id="serviceLog" expression="execution(* com.tab.crm.service..*.*(..))"/>
    <aop:after-returning method="writeLog" pointcut-ref="serviceLog"/>
  </aop:aspect>
</aop:config>

此方案實現「業務零侵入、日誌全覆蓋」,是审計追蹤的經典模式。

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