2010-10-27 43 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()具有,它返回该方法的所有参数。

(但这些所谓的参数/变量,而不是属性)