加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 17:49:21 所属栏目:Java 来源:网络整理
导读:我需要通过使用注释作为切点来接受一些方法及其属性,但是如何访问这些方法属性.我有以下代码,成功地可以在方法运行之前运行代码,但是我不知道如何访问这些attrbiutes. package my.package;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.l
我需要通过使用注释作为切点来接受一些方法及其属性,但是如何访问这些方法属性.我有以下代码,成功地可以在方法运行之前运行代码,但是我不知道如何访问这些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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读