2017-06-19 87 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();