需在呼叫 UserManager.addUser() 前,自動記錄傳入參數與方法名稱,實現安全稽核或日誌記錄。Spring AOP 的 JoinPoint 即可輕鬆取得這些資訊。
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()----------");
}
}
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()---------------");
}
}
<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>
abc
123
addUser
----------checkSecurity()---------------
-------UserManagerImpl.addUser()----------
| 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 提供豐富的執行期上下文,讓橫切關注點(日誌、安全、交易)與業務邏輯徹底解耦。掌握切點運算式與通知類型,即可靈活實現各種攔截需求。