Spring Boot如何通过自定义注解实现日志打印详解
作者:溪源的奇思妙想 时间:2022-07-04 14:10:18
前言
在我们日常的开发过程中通过打印详细的日志信息能够帮助我们很好地去发现开发过程中可能出现的Bug,特别是在开发Controller层的接口时,我们一般会打印出Request请求参数和Response响应结果,但是如果这些打印日志的代码相对而言还是比较重复的,那么我们可以通过什么样的方式来简化日志打印的代码呢?
SpringBoot 通过自定义注解实现权限检查可参考我的博客:SpringBoot 通过自定义注解实现权限检查
正文
Spring AOP
Spring AOP 即面向切面,是对OOP面向对象的一种延伸。
AOP机制可以让开发者把业务流程中的通用功能抽取出来,单独编写功能代码。在业务流程执行过程中,Spring框架会根据业务流程要求,自动把独立编写的功能代码切入到流程的合适位置。
我们通过AOP机制可以实现:Authentication 权限检查、Caching 缓存、Context passing 内容传递、Error handling 错误处理、日志打印等功能,这里我们讲一下怎么用Spring AOP来实现日志打印。
SpringBoot通过自定义注解实现日志打印
Maven依赖
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<optional>true</optional>
</dependency>
<!--Spring AOP-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
ControllerMethodLog.class自定义注解
@Retention: 用来修饰注解,是注解的注解,称为元注解。
@Target:用来说明对象的作用范围
@Documented:用来做标记使用
/**
* 自定义注解用于打印Controller层方式日志
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ControllerMethodLog {
}
这里特别讲一下@Retention,按生命周期来划分可分为3类:
RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃(运行时去动态获取注解信息);
RetentionPolicy.CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期(在编译时进行一些预处理操作);
RetentionPolicy.RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在(做一些检查性的操作);
这3个生命周期分别对应于:Java源文件(.java文件) —> .class文件 —> 内存中的字节码。
Spring AOP切面方法的执行顺序
这里简单介绍一下,切面的执行方法和其执行顺序:
@Around 通知方法将目标方法封装起来
@Before 通知方法会在目标方法调用之前执行
@After 通知方法会在目标方法返回或者异常后执行
@AfterReturning 通知方法会在目标方法返回时执行
@Afterthrowing 通知方法会在目标方法抛出异常时执行
这里以一个返回正常的情况为例:(异常替换最后一步即可)
ControllerMethodLogAspect.class:用于打印日志的切面定义类
注意要在启动类扫描这个class,并且添加 @EnableAspectJAutoProxy(proxyTargetClass = true)
@Slf4j
@Component
@Aspect
public class ControllerMethodLogAspect {
@Pointcut("@annotation(com.xiyuan.demo.annotation.ControllerMethodLog)")
public void pointCut() {
}
/**
* 在切点运行前执行该方法
*/
@Before("pointCut()")
public void doBefore(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ControllerMethodLog annotation = method.getAnnotation(ControllerMethodLog.class);
if (Objects.isNull(annotation)) {
return;
}
String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
log.info("start {}:入参:{}", methodName, JSON.toJSONString(joinPoint.getArgs()));
}
/**
* 在切点运行后,无异常时执行该方法
*
* @param joinPoint
* @param result
*/
@AfterReturning(value = "pointCut()", returning = "result")
public void afterReturn(JoinPoint joinPoint, Object result) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ControllerMethodLog annotation = method.getAnnotation(ControllerMethodLog.class);
if (Objects.isNull(annotation)) {
return;
}
String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
log.info("end {}:响应:{}", methodName, JSON.toJSONString(result));
}
}
验证
getUserById:根据id获取用户的信息
@GetMapping("/getUserById")
@ApiOperation(value = "根据用户id获取用户")
@ControllerMethodLog
public ResponseResult getUserById(@RequestParam(name = "id", required = true) String id) {
UserInfoPojo userInfoPojo = userService.getUserById(id);
return ResponseResult.success(userInfoPojo, ConstantsUtil.QUERY_SUCCESS);
}
Swagger接口信息如下:
IDEA控制台打印信息如下:
来源:https://blog.csdn.net/weixin_40990818/article/details/109039266
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java文件操作输入输出结构详解
Java中synchronized正确使用方法解析
![](https://img.aspxhome.com/file/2023/5/61865_0s.png)
浅谈Spring Cloud Ribbon的原理
![](https://img.aspxhome.com/file/2023/6/76506_0s.png)
Java的idea连接mongodb数据库的详细教程
![](https://img.aspxhome.com/file/2023/1/59711_0s.png)
Java实现图片验证码功能
![](https://img.aspxhome.com/file/2023/5/60995_0s.jpg)
简单聊一聊Java线程池ThreadPoolExecutor
![](https://img.aspxhome.com/file/2023/3/64053_0s.jpg)
Mybatis查询多条记录并返回List集合的方法
你所不知道的Spring自动注入详解
![](https://img.aspxhome.com/file/2023/8/60828_0s.png)
IDEA离线安装maven helper插件的图文教程
![](https://img.aspxhome.com/file/2023/3/78053_0s.jpg)
Spring Boot Logback配置日志过程解析
Java中IO流解析及代码实例详解
获取JsonObject某一未知key的值操作
Java Excel透视表相关操作实现代码
![](https://img.aspxhome.com/file/2023/8/65218_0s.png)
C#的Excel导入、导出
![](https://img.aspxhome.com/file/2023/7/74827_0s.png)
mybatis-plus update更新操作的三种方式(小结)
![](https://img.aspxhome.com/file/2023/9/62639_0s.png)
C#使用ScrapySharp快速从网页采集数据
![](https://img.aspxhome.com/file/2023/8/71728_0s.png)
C# Winform实现圆角无锯齿按钮
![](https://img.aspxhome.com/file/2023/1/68611_0s.png)
Java遍历Properties所有元素的方法实例
详解Java的MyBatis框架与Spring框架整合中的映射器注入
Java类的继承实例详解(动力节点Java学院整理)
![](https://img.aspxhome.com/file/2023/4/65794_0s.png)