Java 使用AOP的自定义注释传递方法参数
我已经用Java 使用AOP的自定义注释传递方法参数,java,aspectj,spring-aop,Java,Aspectj,Spring Aop,我已经用定义了注释 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) 当我在我想显示的方法下使用自定义注释时,然后我想获得方法签名的参数(它们是Object,不是string,int-ant-byte) 有没有简单的方法可以通过AOP的自定义注释获取方法参数?您可以通过ProceedingJoinPoint访问参数: @Around("execution(@com.path.annotation.YourAnnotat
定义了注释
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
当我在我想显示的方法下使用自定义注释时,然后我想获得方法签名的参数(它们是Object,不是string,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;
}
}
如果我的解决方案对您有用,请投票支持我~谢谢;)@有可能指定异常类型吗?例如:
@posterhrowing(“@annotation(methodTimer),throwing=DownstreamException”)
@posterhrowing(@annotation(methodTimer),throwing=DownstreamException”)
@posterhrowing(@annotation(methodTimer)”,throwing=“downstreamException”)
也许您可以求助于GlobalExceptionHandlerinstead@Hearen感谢您的帮助,下面是我的期望。@posterhrowing(value=“(@annotation(LogRequest))”,throwing=“downstreamCallException”)public void logRequestWithBusinessError(JoinPoint JoinPoint,DownstreamCallException DownstreamCallException)
…似乎你应该为此开始一个新问题;)这里的背景不容易理解