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 通知方法会在目标方法抛出异常时执行

这里以一个返回正常的情况为例:(异常替换最后一步即可)

Spring Boot如何通过自定义注解实现日志打印详解

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接口信息如下:

Spring Boot如何通过自定义注解实现日志打印详解

IDEA控制台打印信息如下:

Spring Boot如何通过自定义注解实现日志打印详解

来源:https://blog.csdn.net/weixin_40990818/article/details/109039266

标签:springboot,自定义注解,日志
0
投稿

猜你喜欢

  • java文件操作输入输出结构详解

    2023-07-30 21:48:30
  • Java中synchronized正确使用方法解析

    2021-12-20 13:00:39
  • 浅谈Spring Cloud Ribbon的原理

    2023-07-23 04:11:25
  • Java的idea连接mongodb数据库的详细教程

    2023-11-19 08:07:58
  • Java实现图片验证码功能

    2021-12-07 12:58:55
  • 简单聊一聊Java线程池ThreadPoolExecutor

    2021-10-23 15:56:58
  • Mybatis查询多条记录并返回List集合的方法

    2023-08-08 05:16:48
  • 你所不知道的Spring自动注入详解

    2021-09-04 19:30:08
  • IDEA离线安装maven helper插件的图文教程

    2023-11-28 16:00:24
  • Spring Boot Logback配置日志过程解析

    2022-12-09 18:08:06
  • Java中IO流解析及代码实例详解

    2022-03-08 22:32:16
  • 获取JsonObject某一未知key的值操作

    2023-02-10 15:09:45
  • Java Excel透视表相关操作实现代码

    2022-02-27 00:11:01
  • C#的Excel导入、导出

    2023-09-10 01:00:24
  • mybatis-plus update更新操作的三种方式(小结)

    2023-10-08 14:05:08
  • C#使用ScrapySharp快速从网页采集数据

    2021-08-14 09:25:14
  • C# Winform实现圆角无锯齿按钮

    2022-08-30 01:11:56
  • Java遍历Properties所有元素的方法实例

    2022-09-08 14:58:24
  • 详解Java的MyBatis框架与Spring框架整合中的映射器注入

    2021-06-02 00:32:31
  • Java类的继承实例详解(动力节点Java学院整理)

    2023-01-28 13:19:31
  • asp之家 软件编程 m.aspxhome.com