【问题标题】:Spring Boot Aspect @AroundSpring Boot 方面@Around
【发布时间】:2017-05-16 11:38:48
【问题描述】:

我正在使用 Spring Boot 并尝试记录每个请求的响应时间。 为此,我正在尝试@Around Aspect。 代码:

@Aspect
@Component
public class XYZ {

       @Around("execution(* org.springframework.web.servlet.DispatcherServlet.service(..))")
        public void doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
            // start stopwatch
            long startTime = System.currentTimeMillis();
            System.out.println("Before");
            pjp.proceed();
            long endTime = System.currentTimeMillis();
            // stop stopwatch
            System.out.println("Me here");
        }

}

代码被编译,但问题是当我执行任何控制器方法时,什么都没有发生。我的意思是我的 SOP 应该被打印出来,但事实并非如此。 我错过了什么?

【问题讨论】:

  • 您的端点在控制器中是如何配置的?你使用@RequestMapping 吗?
  • 是的,当我将 @Around 指向我的控制器时,同样的代码也在工作,似乎我无法劫持对 Dispatcher servlet 的请求?
  • 什么都没有发生,因为你告诉它什么也不做。您的方面基本上是在破坏调用链。无论实际调用做了什么,您总是返回 void。 @Around 方面应始终将调用结果返回给proceed(),因此应返回Object 而不是void。此外,当您使用 Spring Boot 时,只需放弃方面并包含 spring-boot-starter-actuator,它已经为您提供了这些指标(以及更多)。

标签: spring-boot aspectj


【解决方案1】:

这个怎么样

@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void requestMapping() {}

@Pointcut("within(path.to your.controller.package.*)")
public void myController() {}

@Around("requestMapping() || myController()")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
   ...............
   joinPoint.proceed();
   ...............
}

【讨论】:

  • 准确吗?我的意思是它将排除服务方法执行的大量开销?我已经使用它计算了响应时间并将其与执行器进行比较,存在时间差异
  • 我认为这并不重要。时差是多少?
  • 可以使用组合版本:@Pointcut("within(path.to your.controller..*) " + "&& @annotation(org.springframework.web.bind.annotation.RequestMapping)" ) public void controllerMethodAnnotatedWithRequestMapping() { }
猜你喜欢
  • 1970-01-01
  • 2019-11-18
  • 2015-07-31
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 2020-05-21
  • 2021-01-31
  • 1970-01-01
相关资源
最近更新 更多