使用Spring AspectJ记录REST资源URL

5
我将使用Spring Boot开发REST API,并希望使用Spring Aspect记录客户端检索的资源URL。我的Aspect类中有以下代码:
@Component
@Aspect
public class Logs {

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

    @Before("allResources()")
    public void apiRequestLog(JoinPoint jp) {    
        LogManager.getLogger(jp.getSignature().getDeclaringTypeName()).info("------------------------- o -------------------------");
        String log = jp.getSignature().getName() + " >>>";
        for (Object arg : jp.getArgs()) {
            log += "\n   ARG: " + arg;
        }
        LogManager.getLogger(jp.getSignature().getDeclaringTypeName()).info(log);

    }
}

我不知道如何将RequestMapping对象作为建议的参数传递,并获取URL路径。

2个回答

10
您可以让Spring将客户端的请求注入到您的切面中:
@Component
@Aspect
public class Logs {
   @Autowired(required = false)
   private HttpServletRequest request;
...

客户端调用的原始URL可以通过在before方法中使用以下方式检索:
request.getRequestURL();

1
为什么这个可以工作?难道不是每一个HTTP请求都会创建一个HttpServletRequest实例吗?Spring如何在单例Aspect实例中自动装配不同的HttpServletRequest? - JaskeyLam

6

不使用自动装配的替代方案:

@Around("isRestController()")
public Object logApiCall(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
    .getRequest();
    log.debug("{} {} from {}",
    request.getMethod(),
    request.getRequestURI(),
    request.getRemoteAddr());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接