1、导包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、记录接口信息
@Aspect
@Component
public class AroundAopConfig {
@Pointcut("execution(public * com.example.aop.controller..*.*(..))")
public void aop(){}
/**
* around一定使用,ProceedingJoinPoint
* 可以控制方法是否继续往下执行,作全局验证
* @param joinPoint
*/
@Around("aop()")
public void aroundAop(ProceedingJoinPoint joinPoint) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
System.out.println("请求地址"+request.getRequestURI());
System.out.println("请求方式" + request.getMethod());
String name = joinPoint.getTarget().getClass().getName();
System.out.println("请求类名" + name);
System.out.println("请求参数" + JSON.toJSONString(joinPoint.getArgs()));
System.out.println("返回参数" + JSON.toJSONString(joinPoint.proceed()));
}
}
2.1、测试接口
aop记录正常
2.2 测试异常
aop记录到了入参,回参没有记录,可以通过异常处理记录异常信息
3、around做接口校验,如果直接return,那么aop会拦截,不继续往下走
3.1、 在aop中加入拦截方法
@Around("aop()")
public Object aroundAop(ProceedingJoinPoint joinPoint) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
System.out.println("请求地址"+request.getRequestURI());
if (true) {
System.out.println("不满足条件,你给我停下来·····");
return "你被我拦截了";
}
System.out.println("请求方式" + request.getMethod());
String name = joinPoint.getTarget().getClass().getName();
System.out.println("请求类名" + name);
System.out.println("请求参数" + JSON.toJSONString(joinPoint.getArgs()));
System.out.println("返回参数" + JSON.toJSONString(joinPoint.proceed()));
return joinPoint.proceed();
}
如果aop的返回类型是object,那么在最后一定要返回
joinPoint.proceed()
,否则程序会被中断
如果返回类型是void,直接return就行,最后也不需要加return joinPoint.proceed();
3.2、修改接口
@PostMapping("/test")
public User test(@RequestBody User user) {
System.out.println("进入方法·····");
user.setId("test");
user.setName("test");
return user;
}
3.3、测试
方法被拦截下来,并且接口中的语句没有打印出来