java - 如何使用 Spring Boot 和 Aspect 记录请求正文

标签 java spring aspectj spring-aop

我创建了一个方面来记录在 Controller 函数中传递的请求正文:

这就是我正在尝试的

@Pointcut("execution(* com.test.test.test.controller.*.* (..))")
  public void executeController() {}

  @Pointcut("execution(* com.test.test.common.exception.*.* (..))")
  public void executeExceptionAdvice() {}

  @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) || "
      + "@annotation(org.springframework.web.bind.annotation.PostMapping) || "
      + "@annotation(org.springframework.web.bind.annotation.PutMapping) ||"
      + "@annotation(org.springframework.web.bind.annotation.ExceptionHandler)")
  public void logRequestMapping() {}

  @Before("logRequestMapping() && executeController() && args(..,@RequestBody requestBody) ")
  public void logRequestBody(JoinPoint joinPoint, Object requestBody) {
    LOGGER = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
    LOGGER.info("Method : {},Request Body:{}",
        LOGGER.getName() + "." + joinPoint.getSignature().getName(),
        MaskingUtil.jsonifyAndMask(requestBody));
  }

现在,spring不再与@RequestBody匹配,而是将参数与..匹配,即概括参数并记录传递的所有内容而不是请求正文。我只想记录请求正文,如果它是null 它不会打印任何内容。

最佳答案

您已经找到了我的相关答案,但我在为您准备了示例后才注意到错误答案下评论中的链接。顺便说一句,我使用了纯 POJO + AspectJ,而不是 Spring AOP(只有类路径上的 Spring 库以便能够解析注释),但方面应该是相同的。

P.S.:我的示例更适合您的问题,因为这里的切入点专门匹配带有 @RequestBody 注释的目标方法。在另一个示例中,您必须匹配所有方法,然后在运行时进行过滤。

虚拟目标类:

我使用两个类来测试您的两个包名称。否则它们是相同的。

package com.test.test.test.controller;

import org.springframework.web.bind.annotation.*;

public class MyController {
  // These should trigger the aspect
  @RequestMapping public String one(int number, @RequestBody String name) { return "Hey!"; }
  @PostMapping public void two(int number, @RequestBody String name) {}
  @PutMapping public String three(@RequestBody String name) { return "Ho!"; }
  @ExceptionHandler public void four(@RequestBody String name) {}

  // These should *not* trigger the aspect
  public String noAnnotation(@RequestBody String name) { return "No annotation"; }
  public String alsoNoAnnotation(String name) { return "Also no annotation"; }
  @RequestMapping public String five(int number, String name) { return "foo"; }
  @PostMapping public void six(int number, String name) {}
  @PutMapping public String seven(String name) { return "bar"; }
  @ExceptionHandler public void eight(String name) {}
}
package com.test.test.common.exception;

import org.springframework.web.bind.annotation.*;

public class MyExceptionHandler {
  // These should trigger the aspect
  @RequestMapping public String one(int number, @RequestBody String name) { return "Hey!"; }
  @PostMapping public void two(int number, @RequestBody String name) {}
  @PutMapping public String three(@RequestBody String name) { return "Ho!"; }
  @ExceptionHandler public void four(@RequestBody String name) {}

  // These should *not* trigger the aspect
  public String noAnnotation(@RequestBody String name) { return "No annotation"; }
  public String alsoNoAnnotation(String name) { return "Also no annotation"; }
  @RequestMapping public String five(int number, String name) { return "foo"; }
  @PostMapping public void six(int number, String name) {}
  @PutMapping public String seven(String name) { return "bar"; }
  @ExceptionHandler public void eight(String name) {}
}

驱动程序应用程序:

package de.scrum_master.app;

import com.test.test.common.exception.MyExceptionHandler;
import com.test.test.test.controller.MyController;

public class Application {
  public static void main(String[] args) {
    MyController controller = new MyController();
    // These should trigger the aspect
    controller.one(1, "one");
    controller.two(2, "two");
    controller.three("three");
    controller.four("four");
    // These should *not* trigger the aspect
    controller.noAnnotation("none");
    controller.five(1, "five");
    controller.six(2, "six");
    controller.seven("seven");
    controller.eight("eight");
    controller.alsoNoAnnotation("none either");

    MyExceptionHandler handler = new MyExceptionHandler();
    // These should trigger the aspect
    handler.one(1, "one");
    handler.two(2, "two");
    handler.three("three");
    handler.four("four");
    // These should *not* trigger the aspect
    handler.noAnnotation("none");
    handler.five(1, "five");
    handler.six(2, "six");
    handler.seven("seven");
    handler.eight("eight");
    handler.alsoNoAnnotation("none either");
  }
}

方面:

package de.scrum_master.aspect;

import java.lang.annotation.Annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.bind.annotation.RequestBody;

@Aspect
public class MyAspect {
  @Pointcut("execution(* com.test.test.test.controller..*(.., @org.springframework.web.bind.annotation.RequestBody (*), ..))")
  public void executeController() {}

  @Pointcut("execution(* com.test.test.common.exception..*(.., @org.springframework.web.bind.annotation.RequestBody (*), ..))")
  public void executeExceptionAdvice() {}

  @Pointcut(
      "@annotation(org.springframework.web.bind.annotation.RequestMapping) || " +
      "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
      "@annotation(org.springframework.web.bind.annotation.PutMapping) ||" +
      "@annotation(org.springframework.web.bind.annotation.ExceptionHandler)"
    )
  public void logRequestMapping() {}

  @Before(
    "logRequestMapping() &&" +
    "(executeController() || executeExceptionAdvice())"
  )
  public void logRequestBody(JoinPoint thisJoinPoint) {
    MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();
    Annotation[][] annotationMatrix = methodSignature.getMethod().getParameterAnnotations();
    int index = -1;
    for (Annotation[] annotations : annotationMatrix) {
      index++;
      for (Annotation annotation : annotations) {
        if (!(annotation instanceof RequestBody))
          continue;
        Object requestBody = thisJoinPoint.getArgs()[index];
        System.out.println(thisJoinPoint);
        System.out.println("  Request body = " + requestBody);
      }
    }
  }
}

控制台日志:

execution(String com.test.test.test.controller.MyController.one(int, String))
  Request body = one
execution(void com.test.test.test.controller.MyController.two(int, String))
  Request body = two
execution(String com.test.test.test.controller.MyController.three(String))
  Request body = three
execution(void com.test.test.test.controller.MyController.four(String))
  Request body = four
execution(String com.test.test.common.exception.MyExceptionHandler.one(int, String))
  Request body = one
execution(void com.test.test.common.exception.MyExceptionHandler.two(int, String))
  Request body = two
execution(String com.test.test.common.exception.MyExceptionHandler.three(String))
  Request body = three
execution(void com.test.test.common.exception.MyExceptionHandler.four(String))
  Request body = four

关于java - 如何使用 Spring Boot 和 Aspect 记录请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50486156/

相关文章:

java - 将类路径资源注入(inject) Spring 3 bean

java - 通过字段表示的未满足的依赖关系(Spring Boot v 1.5.1)

java - AspectJ:跟踪新对象初始化

java - 检查用户手指索引或类型

java - ByteBuffer 可以实现 DataOutput/DataInput 吗?

java - Spring Security 中的 AuthenticationSuccessHandler

java - 尝试使用 Jackson 加载配置时出现异常

java - 将 @Autowired 与 AspectJ 和 Springboot 一起使用

java - apache2.4.6 wstunnel 代理到 tomcat 7 错误意外 200 repsonse

Java foreach循环找不到现有的列表元素