Pass method argument in Aspect of custom annotation

前端 未结 5 1999
说谎
说谎 2021-02-13 03:14

I\'m trying to use something similar to org.springframework.cache.annotation.Cacheable :

Custom annotation:

@Target(ElementType.METHOD)
             


        
5条回答
  •  难免孤独
    2021-02-13 03:59

    Your annotation can be used with methods with more than 1 parameter, but that doesn't mean you can't use the arguments array. Here's a sollution:

    First we have to find the index of the "id" parameter. This you can do like so:

     private Integer getParameterIdx(ProceedingJoinPoint joinPoint, String paramName) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    
        String[] parameterNames = methodSignature.getParameterNames();
        for (int i = 0; i < parameterNames.length; i++) {
            String parameterName = parameterNames[i];
            if (paramName.equals(parameterName)) {
                return i;
            }
        }
        return -1;
    }
    

    where "paramName" = your "id" param

    Next you can get the actual id value from the arguments like so:

     Integer parameterIdx = getParameterIdx(joinPoint, "id");
     Long id = joinPoint.getArgs()[parameterIdx];
    

    Of course this assumes that you always name that parameter "id". One fix there could be to allow to specify the parameter name on the annotation, something like

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface CheckEntity {
        String message() default "Check entity msg";
        String key() default "";
        String paramName() default "id";
    }
    

提交回复
热议问题