springboot使用自定义注解实现aop切面日志
作者:原野灬 发布时间:2023-11-11 09:14:48
平时我们在开发过程中,代码出现bug时为了更好的在服务器日志中寻找问题根源,会在接口的首尾打印日志,看下参数和返回值是否有问题。但是手动的logger.info() 去编写时工作量较大,这时我们可以使用AOP切面,为所有接口的首尾打印日志。
实现AOP切面日志一般有两种方式:
1、拦截所有接口controller,在首尾打印日志
2、拦截指定注解的接口,为有该注解的接口首尾打印日志
我们尝试用自定义注解来实现AOP日志的打印,这样拥有更高的灵活性。废话不多说,我们开始
1. 导入切面需要的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 自定义注解 AOPLog , 指定注解使用在方法上, 指定在运行时有效
Target:描述了注解修饰的对象范围
METHOD:用于描述方法
PACKAGE:用于描述包
PARAMETER:用于描述方法变量
TYPE:用于描述类、接口或enum类型
Retention: 表示注解保留时间长短
SOURCE:在源文件中有效,编译过程中会被忽略
CLASS:随源文件一起编译在class文件中,运行时忽略
RUNTIME:在运行时有效
只有定义为 RetentionPolicy.RUNTIME(在运行时有效)时,我们才能通过反射获取到注解,然后根据注解的一系列值,变更不同的操作。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author buer
* @date 2019/12/26
*/
// 指定注解使用在方法上
@Target(ElementType.METHOD)
// 指定生效至运行时
@Retention(RetentionPolicy.RUNTIME)
public @interface AOPLog {
/**
* 指定是否详情显示
* true 显示详情, 默认false
*
* @return
*/
boolean isDetail() default false;
}
3. 设置切面类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @author buer
* @date 2019/12/26
* @description //TODO
*/
// 指定切面类
@Aspect
// 注入容器
@Component
public class AOPLogAspect {
private static Logger log = LoggerFactory.getLogger(AOPLogAspect.class);
/**
* 指定切点, 切点的位置是存在该注解com.xingyun.xybb.demo.annotation.AOPLog
*/
@Pointcut("@annotation(com.xingyun.xybb.demo.annotation.AOPLog)")
public void logPointCut() {
}
/**
* 环绕通知, 该处写具体日志逻辑
*
* @param joinPoint
*/
@Around("logPointCut()")
public void logAround(ProceedingJoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 获取方法名称
String methodName = signature.getName();
// 获取入参
Object[] param = joinPoint.getArgs();
StringBuilder sb = new StringBuilder();
for (Object o : param) {
sb.append(o).append("; ");
}
log.info("进入方法[{}], 参数有[{}]", methodName, sb.toString());
String resp = "";
try {
Object proceed = joinPoint.proceed();
resp = JSON.toJSONString(proceed, SerializerFeature.WriteMapNullValue);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
// 获取方法上的注解,判断如果isDetail值为true,则打印结束日志
Method method = signature.getMethod();
AOPLog annotation = method.getAnnotation(AOPLog.class);
boolean isDetail = annotation.isDetail();
if (isDetail) {
log.info("方法[{}]执行结束, 返回值[{}]", methodName, resp);
}
}
}
4. 编写测试接口, 测试切面日志是否生效
import com.xingyun.xybb.common.response.XyResponseEntity;
import com.xingyun.xybb.demo.annotation.AOPLog;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author buer
* @date 2019/12/26
* @description //TODO
*/
@RestController
public class TestAOPLogController {
// 指定注解@AOPLog
@AOPLog
@GetMapping("/testAOP")
public ResponseEntity<?> testAOPLog() {
return XyResponseEntity.ok();
}
// 指定注解@AOPLog, 同时isDetail = true
@AOPLog(isDetail = true)
@GetMapping("/testAOPLogDetail")
public ResponseEntity<?> testAOPLogDetail() {
return XyResponseEntity.ok();
}
}
5. 分别请求两测试接口
http://localhost:8499/demo/testAOP
http://localhost:8499/demo/testAOPLogDetail
控制台打印出
2019-12-26 14:00:56.336 ***.AOPLogAspect : 进入方法[testAOPLog], 参数有[]
2019-12-26 14:01:00.372 ***.AOPLogAspect : 进入方法[testAOPLogDetail], 参数有[]
2019-12-26 14:01:00.373 ***.AOPLogAspect : 方法[testAOPLogDetail]执行结束, 返回值[{"body":{"retCode":200,"retEntity":null,"retMsg":"OK"},"headers":{},"statusCode":"OK","statusCodeValue":200}]
由此可看出,AOP切面拦截成功,打印出了日志,同时设置了 isDetail = true 时,打印出了结束日志。
自定义注解实现AOP切面打印日志完成。
来源:https://blog.csdn.net/lp2388163/article/details/103714079


猜你喜欢
- 对于简单的场景来讲,在MEF中导入依赖模块非常简单,只要用ImportAttribute标记依赖的成员,MEF模块会自动找到并创建该模块。但
- 将DataGrid中上面这个表头变成下面的两行表头,你会怎么实现?很巧妙地截断和补充td tr来实现来源:http://www.cnsend
- 一、Spring Bean 集合注入在【Spring学习笔记(三)】已经讲了怎么注入基本数据类型和引用数据类型,接下来介绍如何注入比较特殊的
- 一.使用场景一次请求需要往数据库插入多条数据时,可以节省大量时间,mysql操作在连接和断开时的开销超过本次操作总开销的40%。二.实现方法
- 本文实例讲述了C#实现IP摄像头的方法。分享给大家供大家参考。具体实现方法如下:#region IP摄像头代码/// <summary
- 由于项目需要做一些图形展示,所以就想到了使用Directx和OpenGL来绘图,但项目准备使用C#来开发(大家比较熟悉C#),在网上看了相关
- java类型转换 Integer String Long Float Double Date1如何将字串 String 转换成整数 int?
- Java中的字符串常量池Java中字符串对象创建有两种形式,一种为字面量形式,如String str = "droid"
- 如下所示:if(File.Exists(path)){// 是文件}else if(Directory.Exists(path)){// 是
- 1. Stack1.1 介绍Stack 栈是 Vector 的一个子类,它实现了一个标准的后进先出的栈。它的底层是一个数组。堆栈只定义了默认
- Maven依赖:<dependency><groupId>de.rototor.jeuclid</groupI
- 抛砖今天使用monio做S3存储时,添加云服务器初始化时一直在构建客户端抛出异常。MinioClient.builder() //NoCla
- 本文实例为大家分享了 Android微信选择图片的具体代码,和微信拍照功能,供大家参考,具体内容如下1.Android6.0系统,对于权限的
- 描述:由于产品需求,要求含有EditText的界面全屏显示,最好的解决方式是使用AndroidBug5497Workaround.assis
- 前言日常开发中,我们可能会碰到需要进行防重放与操作幂等的业务,本文记录SpringBoot实现简单防重与幂等防重放,防止数据重复提交操作幂等
- 前文传送门:NioSocketChannel注册到selector我们回到AbstractUnsafe的register0()方法:priv
- 一,简介Feign使得 Java HTTP 客户端编写更方便。Feign 灵感来源于Retrofit、JAXRS-2.0和WebSocket
- 今天重新装了编译器,结果崩无极限,真是日了狗了了。刚刚才知道问题在哪边。好了,说正事,对于ios开发我没接触,不是很了解,百度了半天,差不多
- 简述偶然看到一篇关于阿里新orm框架的文章,好奇的点了进去。开发后端多年,看到这个还是有点兴奋的。常用mysql的orm框架mybatis、
- 背景:今天新生成一个springboot项目,然而启动日志,还有mybatis的详细日志无法打印出来,自写程序中打印的日志可以输出;网上找了