java - 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 {
}
解决方案
您可以尝试将带有所需内容的字符串添加到注释中:
@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();
}
推荐阅读
- reactjs - 创建动态按需输入字段
- c++ - 为什么我的程序的输出不断变化?EAX寄存器不断变化的值?
- c# - 如何在 v5 中为 Swagger 定义相对路径?
- c# - JPEG 位图元数据保存失败,EXIF 缩略图较大
- python - 有没有办法计算 make_blob 生成的数据集的 cluster_std?
- cron - 为什么我的 crontab 不能使用 /etc/crontab 文件
- maven - Java 二进制文件的 Sonarqube 无效值
- nginx - 上游在访问 https 域时从上游读取响应标头时未发送有效的 HTTP/1.0 标头
- mysql - 我知道 PIVOT 命令可以转换数据集,这是正确的方法吗?
- c - C 中将元素添加到数组的函数在多次运行时会产生意外代码