首页 > 解决方案 > 使用 AOP 的自定义注解传递方法参数

问题描述

我已经定义了注释
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)

当我在要考虑的方法下使用自定义注释时,然后我想获取方法签名的参数(它们是对象,而不是字符串,int ant 字节)。

有没有简单的方法通过 AOP 的自定义注释来获取方法参数?

标签: javaaspectjspring-aop

解决方案


一个简单的演示可以:

@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;
    }
}

推荐阅读