首页 > 解决方案 > Spring AOP/AspectJ 记录方法的执行时间,但如何将参数传递给它?(春季启动 API)

问题描述

我在我的 Spring Boot API 中使用 Spring AOP/AspectJ 在 Java 中进行注释@TrackExecutionTime,我可以对任何方法进行注释,并记录该方法运行所花费的总时间。这目前在我的 Spring 启动中工作。我的问题是,我的 API 每天会受到数千次攻击,我想用这个执行时间记录一些其他独特的信息,这样我就可以通过我的日志跟踪/跟踪每个请求。我可以使用的一些数据是与来自 JSON 的 POST 请求正文一起发送的,但我看不到如何将这些参数传递到此注释的定义中 - 任何人都可以帮忙吗?

我想从这个客户对象传递一些参数(客户名字、姓氏等),这是客户端将作为 JSON 发布到我的 API 到我的注释记录器的 requestBody:

@RestController
public class CustomersController implements CustomersApi {

    @Autowired
    private CustomerService customerService;

      return ResponseEntity.ok(offersService.fetchCustomer(Customer, clientId));
    }

我为这样的注释定义了具体类和接口。这是我想传递 Customer 对象的地方,这样我就可以记录名字或姓氏:


@Aspect
@Component
@Slf4j
@ConditionalOnExpression("${aspect.enabled:true}")
public class ExecutionTimeAdvice {

    @Around("@annotation(com.mailshine.springboot.aop.aspectj.advise.TrackExecutionTime)")
    public Object executionTime(ProceedingJoinPoint point) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object object = point.proceed();
        long endtime = System.currentTimeMillis();

        log.info("Class Name: "+ point.getSignature().getDeclaringTypeName() +". Method Name: "+ point.getSignature().getName() + ". Time taken for Execution is : " + (endtime-startTime) +"ms");
        return object;
    }
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {
}

标签: javaspringaopaspectj

解决方案


您可以尝试将带有所需内容的字符串添加到注释中:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {
    String getContent() default "";
}

在方法上使用它:

@TrackExecutionTime(getContent = "something")
private static void someMethod(...)

然后根据建议解析该内容:

@Around("@annotation(myAnnotation)") 
public Object executionTime(ProceedingJoinPoint point, TrackExecutionTime myAnnotation)throws Throwable {
    ...
    String content = myAnnotation.getContent();
}

推荐阅读