前言
项目里在调用别人接口时,需要把调用接口的情况入参和出参都进行一下记录,碰到这种情况,我不想在每个调用接口的方法里都写一遍同样的代码,所以就想到用aop来解决这个需求,这篇文章就是讲解下aop的简单使用。
1.导入依赖
<!-- AOP 切面-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.编写一个切面类
package com.example.springbootdemologaop.aop;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootdemologaop.exception.CheckException;
import com.example.springbootdemologaop.util.RedisUtils;
import com.example.springbootdemologaop.util.JWTUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* 使用AOP记录请求参数和返回结果
*/
@Component
@Aspect
public class TestAspect {
private static final Logger logger=LoggerFactory.getLogger(TestAspect.class);
@Autowired
private RedisUtils redisUtils;
/**
* 统一切点,对com.example.springbootdemologaop.controller及其子包中所有的类的所有方法切面
*/
@Pointcut("execution(public * com.example.springbootdemologaop.controller..*.*(..))")
public void webLog() {
}
/**
* 前置通知:方法调用前被调用
* @param joinPoint
* @throws Throwable
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
logger.info("前置通知............");
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 打印请求内容
logger.info("===================请求内容======================");
logger.info("请求地址 : " + request.getRequestURL());
logger.info("请求方式 : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("请求类名称 : " + joinPoint.getSignature().getDeclaringTypeName());
logger.info("请求类方法名称 : " + joinPoint.getSignature().getName());
logger.info("请求参数 : " + Arrays.toString(joinPoint.getArgs()));
logger.info("===================请求内容======================");
}
/**
* 后置返回通知
* @param result
* @throws Throwable
*/
@AfterReturning(returning = "result",pointcut = "webLog()")
public void doAfterReturning(Object result) throws Throwable {
// 处理完请求,返回内容
logger.info("后置返回通知-->RESPONSE : " + result);
}
}
3.代码测试
package com.example.springbootdemologaop.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/sayHello")
public String sayHello(String name){
return "hello "+name;
}
}
4.测试结果