2017-06-19 89 views
0

我正在使用Spring Boot开发REST API,并且我想记录客户使用Spring Aspect检索的资源的URL。我的看点类有这样的代码:使用Spring AspectJ登录REST资源URL

@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路径。

回答

1

你可以让Spring注入客户端的请求到您的方面:

@Component 
@Aspect 
public class Logs { 
    @Autowired(required = false) 
    private HttpServletRequest request; 
... 

客户端调用原始URL然后可以从在之前-方法通过检索:

request.getRequestURL();