使用 AOP 的自定义注解传递方法参数
Pass method parameter with custom annotation of AOP
我已经用
定义了注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
当我在我想要方面的方法下使用自定义注释时,然后我想获取方法签名的参数(它们是对象,而不是字符串,int ant byte)。
有没有简单的方法获取带有AOP自定义注解的方法参数?
您可以通过 ProceedingJoinPoint
:
访问参数
@Around("execution(@com.path.annotation.YourAnnotation * *(..)) && @annotation(annotation)")
public Object execute(final ProceedingJoinPoint pjp, final YourAnnotation annotation) throws Throwable {
Object result = pjp.proceed();
// Here is the method arguments
Object[] args = pjp.getArgs();
return result;
}
一个简单的演示可以是:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodTimer {
}
以及方面处理程序:
@Aspect
@Slf4j
@Component
public class TimeCounterAspect {
@Around("@annotation(methodTimer)")
public Object logMethodRequests(ProceedingJoinPoint joinPoint, MethodTimer methodTimer)
throws Throwable {
Long start = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String methodName = method.getName();
Object[] myArgs = joinPoint.getArgs();
Object obj = null;
try {
obj = joinPoint.proceed();
} catch (Exception e) {
throw e;
} finally {
log.info("Retrieving timeCost: {} ms in Method: {} args: {}",
System.currentTimeMillis() - start, methodName, Arrays.deepToString(myArgs));
}
return obj;
}
}
我已经用
定义了注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
当我在我想要方面的方法下使用自定义注释时,然后我想获取方法签名的参数(它们是对象,而不是字符串,int ant byte)。
有没有简单的方法获取带有AOP自定义注解的方法参数?
您可以通过 ProceedingJoinPoint
:
@Around("execution(@com.path.annotation.YourAnnotation * *(..)) && @annotation(annotation)")
public Object execute(final ProceedingJoinPoint pjp, final YourAnnotation annotation) throws Throwable {
Object result = pjp.proceed();
// Here is the method arguments
Object[] args = pjp.getArgs();
return result;
}
一个简单的演示可以是:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodTimer {
}
以及方面处理程序:
@Aspect
@Slf4j
@Component
public class TimeCounterAspect {
@Around("@annotation(methodTimer)")
public Object logMethodRequests(ProceedingJoinPoint joinPoint, MethodTimer methodTimer)
throws Throwable {
Long start = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String methodName = method.getName();
Object[] myArgs = joinPoint.getArgs();
Object obj = null;
try {
obj = joinPoint.proceed();
} catch (Exception e) {
throw e;
} finally {
log.info("Retrieving timeCost: {} ms in Method: {} args: {}",
System.currentTimeMillis() - start, methodName, Arrays.deepToString(myArgs));
}
return obj;
}
}