2010-10-27 107 views
9

我需要通過使用註釋作爲切點來介紹一些方法及其屬性,但是如何訪問這些方法屬性。我有以下代碼可以在方法運行之前成功運行代碼,但我不知道如何訪問這些屬性。如何使用Spring AOP(AspectJ風格)訪問方法屬性?

package my.package; 

import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.Around; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Pointcut; 

@Aspect 
public class MyAspect { 

@Pointcut(value="execution(public * *(..))") 
public void anyPublicMethod() { 
} 

@Around("anyPublicMethod() && @annotation(myAnnotation)") 
public Object myAspect(ProceedingJoinPoint pjp, MyAnnotation myAnnotation) 
    throws Throwable { 

    // how can I access method attributes here ? 
    System.out.println("hello aspect!"); 
    return pjp.proceed(); 
} 
} 

回答

13

您可以從ProceedingJoinPoint對象讓他們:

@Around("anyPublicMethod() && @annotation(myAnnotation)") 
public Object myAspect(final ProceedingJoinPoint pjp, 
    final MyAnnotation myAnnotation) throws Throwable{ 

    // retrieve the methods parameter types (static): 
    final Signature signature = pjp.getStaticPart().getSignature(); 
    if(signature instanceof MethodSignature){ 
     final MethodSignature ms = (MethodSignature) signature; 
     final Class<?>[] parameterTypes = ms.getParameterTypes(); 
     for(final Class<?> pt : parameterTypes){ 
      System.out.println("Parameter type:" + pt); 
     } 
    } 

    // retrieve the runtime method arguments (dynamic) 
    for(final Object argument : pjp.getArgs()){ 
     System.out.println("Parameter value:" + argument); 
    } 

    return pjp.proceed(); 
} 
+0

確定現在即時得到它,但它返回奇怪的參數。 org.springframework.s[email protected]8c666a org.springframework.security.web.context.Ht[email protected]197d20c。我的方法是使用@RequestMapping和我自己的註釋的Spring控制器。爲什麼當它給HttpServletRequest對象作爲params時,它給我一些Spring Security對象? – newbie 2010-10-27 09:16:01

+0

這些是原始http請求對象的春季代理。請參閱我的更新回答:您可以同時獲得已定義的參數類型(靜態分析)和實際運行時參數(動態分析) – 2010-10-27 09:32:09

+0

如何獲取靜態參數值(在本例中爲HttpServletRequest對象)? – newbie 2010-10-27 10:02:20

5

ProceedingJoinPointpjp.getArgs()具有,它返回該方法的所有參數。

(但這些所謂的參數/變量,而不是屬性)