最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Spring?AOP實(shí)現(xiàn)用戶操作日志功能

 更新時(shí)間:2022年05月23日 08:57:23   作者:小馮同學(xué)  
這篇文章主要介紹了使用Spring?AOP實(shí)現(xiàn)了用戶操作日志功能,功能實(shí)現(xiàn)需要一張記錄日志的log表,結(jié)合示例代碼給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

我使用Spring AOP實(shí)現(xiàn)了用戶操作日志功能

今天答辯完了,復(fù)盤了一下系統(tǒng),發(fā)現(xiàn)還是有一些東西值得拿出來和大家分享一下。

需求分析

系統(tǒng)需要對(duì)用戶的操作進(jìn)行記錄,方便未來溯源

首先想到的就是在每個(gè)方法中,去實(shí)現(xiàn)記錄的邏輯,但是這樣做肯定是不現(xiàn)實(shí)的,首先工作量大,其次違背了軟件工程設(shè)計(jì)原則(開閉原則)

這種需求顯然是對(duì)代碼進(jìn)行增強(qiáng),首先想到的是使用 SpringBoot 提供的 AOP 結(jié)合注解的方式來實(shí)現(xiàn)

功能實(shí)現(xiàn)

1、 需要一張記錄日志的 Log 表

導(dǎo)出的 sql 如下:

-- mcams.t_log definition

CREATE TABLE `t_log` (
  `log_id` int NOT NULL AUTO_INCREMENT COMMENT '日志編號(hào)',
  `user_id` int NOT NULL COMMENT '操作人id',
  `operation` varchar(128) NOT NULL COMMENT '用戶操作',
  `method` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '操作的方法',
  `params` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '方法的參數(shù)',
  `ip` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '用戶的ip',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '操作時(shí)間',
  `cost_time` int DEFAULT NULL COMMENT '花費(fèi)時(shí)間',
  PRIMARY KEY (`log_id`)
) ENGINE=InnoDB AUTO_INCREMENT=189 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

2、我使用的是 Spring Boot 所以需要引入 spring aop 的 starter

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

如果是使用 spring 框架的,引入 spring-aop 即可

3、Log 實(shí)體類

package com.xiaofengstu.mcams.web.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.Setter;
/**
 * <p>
 * 
 * </p>
 *
 * @author fengzeng
 * @since 2022-05-21
 */
@Getter
@Setter
@TableName("t_log")
public class TLog implements Serializable {
    private static final long serialVersionUID = 1L;
    @TableId(value = "log_id", type = IdType.AUTO)
    private Integer logId;
    /**
     * 操作人id
     */
    @TableField("user_id")
    private Integer userId;
    /**
     * 用戶操作
     */
    @TableField("operation")
    private String operation;
    @TableField("method")
    private String method;
    @TableField("params")
    private String params;
    @TableField("ip")
    private String ip;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @TableField("create_time")
    private LocalDateTime createTime;
    @TableField("cost_time")
    private Long costTime;
}

需要 lombok 插件(@getter && @setter 注解)

4、ILog 注解

package com.xiaofengstu.mcams.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * @Author FengZeng
 * @Date 2022-05-21 00:48
 * @Description TODO
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ILog {
  String value() default "";
}

5、切面類 LogAspect

package com.xiaofengstu.mcams.aspect;
import com.xiaofengstu.mcams.annotation.ILog;
import com.xiaofengstu.mcams.util.ThreadLocalUtils;
import com.xiaofengstu.mcams.web.entity.TLog;
import com.xiaofengstu.mcams.web.service.TLogService;
import lombok.RequiredArgsConstructor;
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.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
/**
 * @Author FengZeng
 * @Date 2022-05-21 00:42
 * @Description TODO
 */
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {
  private final TLogService logService;
  @Pointcut("@annotation(com.xiaofengstu.mcams.annotation.ILog)")
  public void pointcut() {
  }
  @Around("pointcut()")
  public Object around(ProceedingJoinPoint point) {
    Object result = null;
    long beginTime = System.currentTimeMillis();
    try {
      result = point.proceed();
    } catch (Throwable e) {
      e.printStackTrace();
    }
    long costTime = System.currentTimeMillis() - beginTime;
    saveLog(point, costTime);
    return result;
  }
  private void saveLog(ProceedingJoinPoint point, long costTime) {
    // 通過 point 拿到方法簽名
    MethodSignature methodSignature = (MethodSignature) point.getSignature();
    // 通過方法簽名拿到被調(diào)用的方法
    Method method = methodSignature.getMethod();
    TLog log = new TLog();
    // 通過方法區(qū)獲取方法上的 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 + "()");
    // 獲取方法的參數(shù)
    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);
  }
}

因?yàn)槲沂褂玫氖?Mybatis-plus,所以 logService.save(log);是 mybatis-plus 原生的 save operation

這步其實(shí)就是把 log 插入到數(shù)據(jù)庫

6、使用

只需要在方法上加上 @ILog 注解,并設(shè)置它的 value 即可(value 就是描述當(dāng)前 method 作用)

package com.xiaofengstu.mcams.web.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaofengstu.mcams.annotation.ILog;
import com.xiaofengstu.mcams.dto.BasicResultDTO;
import com.xiaofengstu.mcams.enums.RespStatusEnum;
import com.xiaofengstu.mcams.web.entity.TDept;
import com.xiaofengstu.mcams.web.service.TDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fengzeng
 * @since 2022-05-07
 */
@RestController
@RequestMapping("/web/dept")
@RequiredArgsConstructor
public class TDeptController {
  private final TDeptService deptService;
  @ILog("獲取部門列表")
  @GetMapping("/list")
  public BasicResultDTO<List<TDept>> getDeptListByCampId(@RequestParam("campusId") Integer campusId) {
    return new BasicResultDTO(RespStatusEnum.SUCCESS, deptService.list(new QueryWrapper<TDept>().eq("campus_id", campusId)));
  }
  @ILog("通過角色獲取部門列表")
  @GetMapping("/listByRole")
  public BasicResultDTO<List<TDept>> getDeptListByRole() {
    return new BasicResultDTO<>(RespStatusEnum.SUCCESS, deptService.listByRole());
  }
}

數(shù)據(jù)庫:

總結(jié)

如果要對(duì)現(xiàn)有代碼進(jìn)行功能擴(kuò)展,使用 AOP + 注解不妨為一種優(yōu)雅的方式

對(duì) AOP 不熟悉的小伙伴,可以深入了解一下,畢竟是 spring 最重要的特性之一。

到此這篇關(guān)于使用Spring AOP實(shí)現(xiàn)了用戶操作日志功能的文章就介紹到這了,更多相關(guān)Spring AOP用戶操作日志內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • spring中時(shí)間格式化的兩種方法示例講解

    spring中時(shí)間格式化的兩種方法示例講解

    這篇文章主要介紹了spring中時(shí)間格式化的兩種方法,方法一自己格式化,方法二通過配置,結(jié)合實(shí)例代碼講解的非常詳細(xì),文中補(bǔ)充介紹了Spring項(xiàng)目中時(shí)間格式化的方法,需要的朋友可以參考下
    2023-08-08
  • Java中的synchronized重量級(jí)鎖解析

    Java中的synchronized重量級(jí)鎖解析

    這篇文章主要介紹了Java中的synchronized重量級(jí)鎖解析,內(nèi)核需要去申請(qǐng)這個(gè)互斥量,必須要進(jìn)入內(nèi)核態(tài),也就是這里需要用戶態(tài),內(nèi)核態(tài)的切換,狀態(tài)的切換,開銷是比較大的,這就是重型鎖的一個(gè)弊端,需要的朋友可以參考下
    2024-01-01
  • mybatisplus解除分頁限制的實(shí)現(xiàn)

    mybatisplus解除分頁限制的實(shí)現(xiàn)

    這篇文章主要介紹了mybatisplus解除分頁限制的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • springboot集成spring cache緩存示例代碼

    springboot集成spring cache緩存示例代碼

    本篇文章主要介紹了springboot集成spring cache示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-05-05
  • Spring實(shí)戰(zhàn)之設(shè)置普通屬性值的方法示例

    Spring實(shí)戰(zhàn)之設(shè)置普通屬性值的方法示例

    這篇文章主要介紹了Spring實(shí)戰(zhàn)之設(shè)置普通屬性值的方法,結(jié)合實(shí)例形式分析了Spring設(shè)置普通屬性值的方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2019-11-11
  • Java基于Socket實(shí)現(xiàn)HTTP下載客戶端

    Java基于Socket實(shí)現(xiàn)HTTP下載客戶端

    這篇文章主要介紹了Java基于Socket實(shí)現(xiàn)HTTP下載客戶端的相關(guān)資料,感興趣的小伙伴們可以參考一下
    2016-01-01
  • Spring+Quartz配置定時(shí)任務(wù)實(shí)現(xiàn)代碼

    Spring+Quartz配置定時(shí)任務(wù)實(shí)現(xiàn)代碼

    這篇文章主要介紹了Spring+Quartz配置定時(shí)任務(wù)實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • MyBatis動(dòng)態(tài)SQL foreach標(biāo)簽實(shí)現(xiàn)批量插入的方法示例

    MyBatis動(dòng)態(tài)SQL foreach標(biāo)簽實(shí)現(xiàn)批量插入的方法示例

    這篇文章主要介紹了MyBatis動(dòng)態(tài)SQL foreach標(biāo)簽實(shí)現(xiàn)批量插入的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • Spring?Aop常見注解與執(zhí)行順序詳解

    Spring?Aop常見注解與執(zhí)行順序詳解

    這篇文章主要給大家介紹了關(guān)于Spring?Aop常見注解與執(zhí)行順序的相關(guān)資料,文中通過圖文以及實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2022-02-02
  • Java中Scanner使用方式:單行/多行輸入

    Java中Scanner使用方式:單行/多行輸入

    這篇文章主要介紹了Java中Scanner使用方式:單行/多行輸入,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05

最新評(píng)論

蓬安县| 鸡东县| 沙田区| 博罗县| 原平市| 临湘市| 永仁县| 资阳市| 黎川县| 黔南| 晋宁县| 万安县| 中超| 天津市| SHOW| 博客| 卫辉市| 镶黄旗| 平舆县| 临朐县| 庆元县| 江川县| 建宁县| 开化县| 固始县| 锡林浩特市| 义乌市| 黎川县| 开阳县| 伊宁县| 杭锦旗| 永吉县| 宝清县| 灌南县| 太仓市| 宁都县| 萨迦县| 碌曲县| 万山特区| 香港| 沭阳县|