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

Spring AOP 實戰:攔截方法參數與簽名

     編輯:Java 相關知識

場景

需在呼叫 UserManager.addUser() 前,自動記錄傳入參數與方法名稱,實現安全稽核或日誌記錄。Spring AOP 的 JoinPoint 即可輕鬆取得這些資訊。

核心程式碼

1. 介面與實作

public interface UserManager {
    void addUser(String username, String password);
    void deleteUser(int id);
}

public class UserManagerImpl implements UserManager {
    public void addUser(String username, String password) {
        System.out.println("-------UserManagerImpl.addUser()----------");
    }
    public void deleteUser(int id) {
        System.out.println("-------UserManagerImpl.deleteUser()----------");
    }
}

2. 切面類別

public class SecurityHandler {
    public void checkSecurity(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();           // 取得所有參數
        for (Object arg : args) {
            System.out.println(arg);
        }
        System.out.println(joinPoint.getSignature().getName()); // 方法名稱
        System.out.println("----------checkSecurity()---------------");
    }
}

3. Spring XML 配置(Schema-based AOP)

<beans xmlns="https://www.springframework.org/schema/beans"
  xmlns:aop="https://www.springframework.org/schema/aop"
  xsi:schemaLocation="...
  https://www.springframework.org/schema/aop
  https://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

  <bean id="securityHandler" class="com.rx.spring.dynamicmock.SecurityHandler"/>
  <bean id="userManager" class="com.rx.spring.dynamicmock.UserManagerImpl"/>

  <aop:config>
    <aop:aspect id="security" ref="securityHandler">
      <aop:pointcut id="allAddMethod"
        expression="execution(* com.rx.spring.dynamicmock.UserManagerImpl.add*(..))"/>
      <aop:before method="checkSecurity" pointcut-ref="allAddMethod"/>
    </aop:aspect>
  </aop:config>
</beans>

4. 執行結果

abc
123
addUser
----------checkSecurity()---------------
-------UserManagerImpl.addUser()----------

關鍵 API 說明

API用途
joinPoint.getArgs()回傳參數陣列 Object[]
joinPoint.getSignature().getName()取得被攔截方法名稱
joinPoint.getTarget()取得目標物件實例
joinPoint.proceed()環繞通知中繼續執行目標方法

進階:環繞通知修改參數或回傳值

public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
    Object[] args = pjp.getArgs();
    args[0] = "modified_" + args[0];  // 修改第一個參數
    Object result = pjp.proceed(args); // 執行目標方法
    return "WRAPPED_" + result;        // 包裝回傳值
}

總結

Spring AOP 透過 JoinPoint 提供豐富的執行期上下文,讓橫切關注點(日誌、安全、交易)與業務邏輯徹底解耦。掌握切點運算式與通知類型,即可靈活實現各種攔截需求。

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