今天项目完了,复盘了一下系统,发现还是有一些东西值得拿出来和大家分享一下。
需求分析
系统需要对用户的操作进行记录,方便未来溯源
首先想到的就是在每个方法中,去实现记录的逻辑,但是这样做肯定是不现实的,首先工作量大,其次违背了软件工程设计原则(开闭原则)
这种需求显然是对代码进行增强,首先想到的是使用 SpringBoot 提供的 AOP 结合注解的方式来实现
功能实现
1、 需要一张记录日志的 Log 表
导出的 sql 如下:
-- mcams.t_log definitionCREATE TABLE `t_log` ( `log_id` int NOTNULLAUTO_INCREMENT COMMENT'日志编号', `user_id` int NOTNULLCOMMENT'操作人id', `operation` varchar(128) NOTNULLCOMMENT'用户操作', `method` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ciDEFAULTNULLCOMMENT'操作的方法', `params` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ciDEFAULTNULLCOMMENT'方法的参数', `ip` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ciDEFAULTNULLCOMMENT'用户的ip', `create_time` timestampNULLDEFAULTNULLCOMMENT'操作时间', `cost_time` intDEFAULTNULLCOMMENT'花费时间', PRIMARY KEY (`log_id`)) ENGINE=InnoDB AUTO_INCREMENT=189DEFAULTCHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
2、我使用的是 Spring Boot 所以需要引入 spring aop 的 starter#
org.springframework.bootspring-boot-starter-aop
如果是使用 spring 框架的,引入 spring-aop 即可
3、Log 实体类#
packagecom.xiaofengstu.mcams.web.entity;importcom.baomidou.mybatisplus.annotation.IdType;importcom.baomidou.mybatisplus.annotation.TableField;importcom.baomidou.mybatisplus.annotation.TableId;importcom.baomidou.mybatisplus.annotation.TableName;importjava.io.Serializable;importjava.time.LocalDateTime;importcom.fasterxml.jackson.annotation.JsonFormat;importlombok.Getter;importlombok.Setter;/** *
* *@authorfengzeng *@since2022-05-21 */@Getter@Setter@TableName("t_log")publicclassTLogimplementsSerializable{privatestaticfinallong serialVersionUID =1L;@TableId(value ="log_id", type = IdType.AUTO)privateInteger logId;/** * 操作人id */@TableField("user_id")privateInteger userId;/** * 用户操作 */@TableField("operation")privateString operation;@TableField("method")privateString method;@TableField("params")privateString params;@TableField("ip")privateString ip;@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss")@TableField("create_time")privateLocalDateTime createTime;@TableField("cost_time")privateLongcostTime;}
需要 lombok 插件(@getter && @setter 注解)
4、ILog 注解#
packagecom.xiaofengstu.mcams.annotation;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;/** *@AuthorFengZeng *@Date2022-05-21 00:48 *@DescriptionTODO */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public@interfaceILog { String value()default"";}
5、切面类 LogAspect#
packagecom.xiaofengstu.mcams.aspect;importcom.xiaofengstu.mcams.annotation.ILog;importcom.xiaofengstu.mcams.util.ThreadLocalUtils;importcom.xiaofengstu.mcams.web.entity.TLog;importcom.xiaofengstu.mcams.web.service.TLogService;importlombok.RequiredArgsConstructor;importorg.aspectj.lang.ProceedingJoinPoint;importorg.aspectj.lang.annotation.Around;importorg.aspectj.lang.annotation.Aspect;importorg.aspectj.lang.annotation.Pointcut;importorg.aspectj.lang.reflect.MethodSignature;importorg.springframework.core.LocalVariableTableParameterNameDiscoverer;importorg.springframework.stereotype.Component;importorg.springframework.web.context.request.RequestContextHolder;importorg.springframework.web.context.request.ServletRequestAttributes;importjavax.servlet.http.HttpServletRequest;importjava.lang.reflect.Method;importjava.time.LocalDateTime;/** *@AuthorFengZeng *@Date2022-05-21 00:42 *@DescriptionTODO */@Aspect@Component@RequiredArgsConstructorpublicclassLogAspect{privatefinalTLogService logService;@Pointcut("@annotation(com.xiaofengstu.mcams.annotation.ILog)")publicvoidpointcut(){ }@Around("pointcut()")publicObjectaround(ProceedingJoinPoint point){ Object result =null;longbeginTime = System.currentTimeMillis();try{ result = point.proceed(); }catch(Throwable e) { e.printStackTrace(); }longcostTime = System.currentTimeMillis() - beginTime; saveLog(point, costTime);returnresult; }privatevoidsaveLog(ProceedingJoinPoint point,longcostTime){// 通过 point 拿到方法签名 MethodSignature methodSignature = (MethodSignature) point.getSignature(); // 通过方法签名拿到被调用的方法 Method method = methodSignature.getMethod(); TLog log = new TLog(); // 通过方法区获取方法上的 ILog 注解 ILog logAnnotation = method.getAnnotation(ILog.class); if (logAnnotation != null) { log.setOperation(logAnnotation.value()); } String className = point.getTarget().getClass().getName(); String methodName = methodSignature.getName(); log.setMethod(className + "." + methodName + "()"); // 获取方法的参数 Object[] args = point.getArgs(); LocalVariableTableParameterNameDiscoverer l = new LocalVariableTableParameterNameDiscoverer(); String[] parameterNames = l.getParameterNames(method); if (args != null && parameterNames != null) { StringBuilder param = new StringBuilder(); for (int i = 0; i < args.length; i++) { param.append(" ").append(parameterNames[i]).append(":").append(args[i]); } log.setParams(param.toString()); } ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); log.setIp(request.getRemoteAddr()); log.setUserId(ThreadLocalUtils.get()); log.setCostTime(costTime); log.setCreateTime(LocalDateTime.now()); logService.save(log); }}
因为我使用的是 Mybatis-plus,所以 logService.save(log);是 mybatis-plus 原生的 save operation
这步其实就是把 log 插入到数据库
6、使用
只需要在方法上加上 @ILog 注解,并设置它的 value 即可(value 就是描述当前 method 作用)
packagecom.xiaofengstu.mcams.web.controller;importcom.baomidou.mybatisplus.core.conditions.query.QueryWrapper;importcom.xiaofengstu.mcams.annotation.ILog;importcom.xiaofengstu.mcams.dto.BasicResultDTO;importcom.xiaofengstu.mcams.enums.RespStatusEnum;importcom.xiaofengstu.mcams.web.entity.TDept;importcom.xiaofengstu.mcams.web.service.TDeptService;importlombok.RequiredArgsConstructor;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importjava.util.List;/** * <p> * 前端控制器 * </p> * * @author fengzeng * @since 2022-05-07 */@RestController@RequestMapping("/web/dept")@RequiredArgsConstructorpublicclass TDeptController {privatefinalTDeptServicedeptService;@ILog("获取部门列表") @GetMapping("/list") public BasicResultDTO> getDeptListByCampId(@RequestParam("campusId") Integer campusId) {returnnewBasicResultDTO(RespStatusEnum.SUCCESS,deptService.list(newQueryWrapper().eq("campus_id",campusId))); }@ILog("通过角色获取部门列表") @GetMapping("/listByRole") public BasicResultDTO> getDeptListByRole() {returnnewBasicResultDTO<>(RespStatusEnum.SUCCESS,deptService.listByRole()); }}
数据库:
总结
如果要对现有代码进行功能扩展,使用 AOP + 注解不妨为一种优雅的方式
对 AOP 不熟悉的小伙伴,可以深入了解一下,毕竟是 spring 最重要的特性之一。