使用Spring的AOP打印HTTP接口出入?yún)⑷罩?/h1>
前言
最近在維護(hù)一個(gè)運(yùn)營(yíng)端的系統(tǒng),和前端聯(lián)調(diào)的過(guò)程中,經(jīng)常需要排查一些交互上的問(wèn)題,每次都得看前端代碼的傳參和后端代碼的出參,于是打算給HTTP接口加上出入?yún)⑷罩尽?/p>
但看著目前的HTTP接口有點(diǎn)多,那么有什么快捷的方式呢?答案就是實(shí)用Spring的AOP功能,簡(jiǎn)單實(shí)用。
思路
定義個(gè)一個(gè)SpringAOP的配置類,里邊獲取請(qǐng)求的URL、請(qǐng)求的入?yún)?、相?yīng)的出參,通過(guò)日志打印出來(lái)。
SpringBoot的aop依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
示例
1.編寫(xiě)一個(gè)HTTP接口
定義了一個(gè)Controller,里邊就一個(gè)方法,方法請(qǐng)求類型是get,出入?yún)⒍际呛?jiǎn)單的一個(gè)字符串字段。
package com.example.springbootaoplog.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author hongcunlin
*/
@RestController
@RequestMapping("/index")
public class IndexController {
@GetMapping("/indexContent")
public String indexContent(String param) {
return "test";
}
}
2.編寫(xiě)一個(gè)AOP日志配置
這算是本文的重點(diǎn)了,定義一個(gè)AOP的內(nèi)容,首先是切點(diǎn),再者是請(qǐng)求前日志打印,最后請(qǐng)求后日志打印
package com.example.springbootaoplog.config;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* aop日志打印配置
*
* @author hongcunlin
*/
@Slf4j
@Aspect
@Component
public class AopLogConfig {
/**
* 切點(diǎn)路徑:Controller層的所有方法
*/
@Pointcut("execution(public * com.example.springbootaoplog.controller.*.*(..))")
public void methodPath() {
}
/**
* 入?yún)?/span>
*
* @param joinPoint 切點(diǎn)
*/
@Before(value = "methodPath()")
public void before(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String url = requestAttributes.getRequest().getRequestURL().toString();
log.info("請(qǐng)求 = {}, 入?yún)?= {}", url, JSON.toJSONString(joinPoint.getArgs()));
}
/**
* 出參
*
* @param res 返回
*/
@AfterReturning(returning = "res", pointcut = "methodPath()")
public void after(Object res) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String url = requestAttributes.getRequest().getRequestURL().toString();
log.info("請(qǐng)求 = {}, 入?yún)?= {}", url, JSON.toJSONString(res));
}
}
3.結(jié)果測(cè)試
我們通過(guò)瀏覽器的URL,針對(duì)我們編寫(xiě)的http接口,發(fā)起一次get請(qǐng)求:
可以看到,日志里邊打印了我們預(yù)期的請(qǐng)求的URL和出入?yún)⒘耍?/p>
說(shuō)明我們的程序是正確的了。
最后
本文分享了通過(guò)Spring的AOP功能,完成HTTP接口的出入?yún)⑷罩镜拇蛴〉姆椒?,同時(shí)也說(shuō)明,越是基礎(chǔ)的東西,越是實(shí)用。