使用Spring Boot AOP和自定义注解优雅实现操作日志记录

使用Spring Boot AOP和自定义注解优雅实现操作日志记录

大家好,今天我们来聊聊如何在Spring Boot项目中,通过AOP(面向切面编程)和自定义注解,优雅地实现操作日志记录。操作日志对于系统的可维护性和安全性至关重要,它能帮助我们追踪用户行为,排查问题。

什么是AOP?

AOP,全称Aspect-Oriented Programming,面向切面编程。它允许我们将那些与业务逻辑无关的代码(如日志记录、事务管理等)从业务逻辑中分离出来,使代码更加清晰和可维护。

为什么使用AOP来记录操作日志?

  1. 解耦:将日志记录逻辑从业务代码中分离出来,减少代码耦合。
  2. 可维护:日志记录逻辑集中管理,方便维护和修改。
  3. 灵活性:可以根据需要灵活地添加或移除日志记录功能。

实现步骤

我们将通过以下几个步骤来实现操作日志记录:

  1. 创建自定义注解。
  2. 使用AOP拦截带有自定义注解的方法。
  3. 在拦截的方法中记录操作日志。

1. 创建自定义注解

首先,我们需要创建一个自定义注解,用来标记需要记录操作日志的方法。

package com.example.logging;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperationLog {
    String value() default "";
}

2. 使用AOP拦截带有自定义注解的方法

接下来,我们需要创建一个AOP切面类,拦截所有带有@OperationLog注解的方法,并记录操作日志。

package com.example.logging;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class OperationLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(OperationLogAspect.class);

    @Pointcut("@annotation(com.example.logging.OperationLog)")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取注解
        OperationLog operationLog = method.getAnnotation(OperationLog.class);
        String operation = operationLog.value();

        // 获取方法参数
        Object[] args = joinPoint.getArgs();

        // 记录日志
        logger.info("操作日志 - 方法: {}, 操作: {}, 参数: {}", method.getName(), operation, args);
    }
}

3. 在方法上使用自定义注解

最后,我们只需要在需要记录操作日志的方法上使用@OperationLog注解即可。

package com.example.controller;

import com.example.logging.OperationLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @OperationLog("获取用户信息")
    @GetMapping("/user")
    public String getUser() {
        // 模拟获取用户信息
        return "User Info";
    }
}

总结

通过以上步骤,我们实现了一个简单而优雅的操作日志记录功能。使用AOP和自定义注解,不仅让我们的代码更加清晰和可维护,还提高了日志记录的灵活性。

希望这篇文章对你有所帮助。如果你有任何问题或建议,欢迎在评论区留言。感谢阅读!


如果你觉得这个标题还不错,可以继续使用。如果你有其他更好的标题建议,也欢迎分享!

百万大学生都在用的AI写论文工具,篇篇无重复👉: AI写论文

posted @ 2024-07-18 11:08  自足  阅读(105)  评论(0编辑  收藏  举报