【问题标题】:Spring Aspect - How to identify which Pointcut triggers the functionSpring Aspect - 如何识别哪个 Pointcut 触发了函数
【发布时间】:2019-09-25 07:35:07
【问题描述】:

我想以不同的方式记录 Controller 和其他包。我知道我可以为此使用 2 种单独的方法,但这两种方法非常相似,所以我想添加一个代码来检查它是否看起来像这样

@Around("controllerPoint() || theRest()")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
  if( called from controllerPoint() ) {
      execute this short section of code                     # (1)            
  }
// rest of code

这段代码会是什么样子?

另外,如果在我执行 (1) 之后,我想在执行其他包时再次将一个变量传递给同一个方法,我该怎么做?

【问题讨论】:

  • 不要...只需编写 2 个方法并将共享的内容提取到您从两者调用的方法中。尝试将所有这些都硬塞到一个方法中会更容易推理。

标签: spring-boot logging spring-aspects


【解决方案1】:

你可以像下面这样调用方法,它会返回你的方法名

joinPoint.getSignature().getName()

【讨论】:

    【解决方案2】:

    您可以从连接点获取方法名称:

    @Aspect
    @Configuration
    public class TrackingConfig {
    
        @Around("execution(* your.package.Controller.*(..))")
        public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
            String methodName = pjp.getSignature().getName();
            if ("theRest".equals(methodName)) {
                System.out.println("AROUND! theRest ");
            } else if ("controllerPoint".equals(methodName)) {
                System.out.println("AROUND! controllerPoint ");
            }
            return pjp.proceed();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      相关资源
      最近更新 更多