Get method arguments using Spring AOP?

后端 未结 8 1991
陌清茗
陌清茗 2020-11-29 01:13

I am using Spring AOP and have below aspect:

@Aspect
public class LoggingAspect {

    @Before(\"execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..         


        
8条回答
  •  遥遥无期
    2020-11-29 01:48

    If you have to log all args or your method have one argument, you can simply use getArgs like described in previous answers.

    If you have to log a specific arg, you can annoted it and then recover its value like this :

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.PARAMETER)
    public @interface Data {
     String methodName() default "";
    }
    
    @Aspect
    public class YourAspect {
    
     @Around("...")
     public Object around(ProceedingJoinPoint point) throws Throwable {
      Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
      Object[] args = point.getArgs();
      StringBuilder data = new StringBuilder();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        for (int argIndex = 0; argIndex < args.length; argIndex++) {
            for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
                if (!(paramAnnotation instanceof Data)) {
                    continue;
                }
                Data dataAnnotation = (Data) paramAnnotation;
                if (dataAnnotation.methodName().length() > 0) {
                    Object obj = args[argIndex];
                    Method dataMethod = obj.getClass().getMethod(dataAnnotation.methodName());
                    data.append(dataMethod.invoke(obj));
                    continue;
                }
                data.append(args[argIndex]);
            }
        }
     }
    }
    

    Examples of use :

    public void doSomething(String someValue, @Data String someData, String otherValue) {
        // Apsect will log value of someData param
    }
    
    public void doSomething(String someValue, @Data(methodName = "id") SomeObject someData, String otherValue) {
        // Apsect will log returned value of someData.id() method
    }
    

提交回复
热议问题