SpringBoot:通过AOP+注解优雅实现操作日志记录

在开发过程中,我们经常需要记录用户的操作日志,例如用户的登录、新增、修改、删除等操作。为了更加优雅地实现操作日志记录,我们可以借助Spring Boot的AOP和注解来实现。

首先,我们需要创建一个注解@Log,用来声明哪些方法需要记录操作日志。可以在类级别或者方法级别使用该注解。例如:

java 复制代码
@Log("新增用户") // 在方法上使用注解
@PostMapping("/users")
public User createUser(@RequestBody User user) {
    // 创建用户逻辑
}

接下来,我们需要创建一个切面类LogAspect,用来处理@Log注解的逻辑。在切面类中,我们可以获取到方法的参数、返回值等信息,进而记录对应的操作日志。

java 复制代码
@Aspect
@Component
public class LogAspect {

    @Autowired
    private LogService logService;

    @Pointcut("@annotation(com.example.demo.annotation.Log)")
    public void logPointCut() {
    }

    @AfterReturning(pointcut = "logPointCut()", returning = "returnValue")
    public void afterReturning(JoinPoint joinPoint, Object returnValue) {
        // 获取方法的参数、返回值等信息
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        // ...
        // 记录操作日志
        Log log = joinPoint.getMethod().getAnnotation(Log.class);
        logService.saveLog(log.value(), methodName, args, returnValue);
    }
}

在切面类中,我们使用@Pointcut注解来声明@Log注解的切入点,使用@AfterReturning注解来处理方法执行完毕后的逻辑。在afterReturning方法中,我们可以通过joinPoint参数获取到方法的相关信息,并调用logService来保存操作日志。

最后,我们需要定义一个LogService来实现将操作日志保存到数据库或者其他日志存储方式。

java 复制代码
@Service
public class LogService {

    public void saveLog(String action, String methodName, Object[] args, Object returnValue) {
        // 将操作日志保存到数据库或者其他日志存储方式
    }
}

通过以上步骤,我们就可以实现通过AOP+注解优雅地实现操作日志记录了。在需要记录操作日志的方法上添加@Log注解,就可以自动记录对应的操作日志了。

相关推荐
汪汪大队u7 分钟前
续:从 Docker Compose 到 Kubernetes(2)—— 服务优化与排错
网络·后端·物联网·struts·容器
如何原谅奋力过但无声38 分钟前
【灵神高频面试题合集06-08】反转链表、快慢指针(环形链表/重排链表)、前后指针(删除链表/链表去重)
数据结构·python·算法·leetcode·链表
deephub1 小时前
2026 RAG 选型指南:Vector、Graph、Vectorless 该怎么挑
人工智能·python·大语言模型·rag
无风听海1 小时前
MapStaticAssets()深度解析:ASP.NET Core 静态资源交付的现代范式
后端·asp.net
geovindu2 小时前
go: Lock/Mutex Pattern
开发语言·后端·设计模式·golang·互斥锁模式
counterxing2 小时前
AI Agent 做长任务,问题到底 出在哪?
前端·后端·ai编程
aiopencode3 小时前
iOS开发中Xcode安装不完整问题解决方案与配置指南
后端·ios
狐狐生风3 小时前
使用 UV 创建并运行 Python 项目(完整步骤)
python·uv
该用户已不存在3 小时前
别让 Claude Code 果奔,用 Claude Code MCP 与 Skills 打造自动化开发(Part 2)
后端·ai编程·claude
噜噜噜阿鲁~3 小时前
python学习笔记 | 9.2、模块-安装第三方模块
笔记·python·学习