微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 如何使用Spring AOP(AspectJ风格)访问方法属性?

我需要通过使用注释作为切点来接受一些方法及其属性,但是如何访问这些方法属性.我有以下代码,成功地可以在方法运行之前运行代码,但是我不知道如何访问这些attrbiutes.
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();
 }
}

解决方法

您可以从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();
}

原文地址:https://www.jb51.cc/java/123825.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐