【Springboot】基于AOP实现操作日志记录

以下是一个使用Spring Boot和AspectJ实现操作日志记录的简单示例:

  1. 首先,添加依赖到你的pom.xml



<dependencies>
    <!-- 添加Spring Boot的Web依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
 
    <!-- 添加AspectJ的Spring Boot Starter依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
</dependencies>
  1. 创建一个日志实体类OperationLog



public class OperationLog {
    private String user;
    private String operation;
    private String timestamp;
 
    // 省略构造器、getter和setter方法
}
  1. 创建一个日志服务接口OperationLogService



public interface OperationLogService {
    void saveOperationLog(OperationLog operationLog);
}
  1. 实现OperationLogService



@Service
public class OperationLogServiceImpl implements OperationLogService {
    @Override
    public void saveOperationLog(OperationLog operationLog) {
        // 实现保存日志的逻辑,例如写入数据库或文件
        System.out.println("Operation Log: " + operationLog.toString());
    }
}
  1. 创建一个切面类OperationLogAspect



@Aspect
@Component
public class OperationLogAspect {
 
    @Autowired
    private OperationLogService operationLogService;
 
    @Pointcut("execution(* com.yourpackage..*.*(..))") // 根据实际情况配置切点表达式
    public void operationLogPointcut() {
    }
 
    @AfterReturning(pointcut = "operationLogPointcut() && !within(OperationLogAspect)", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        OperationLog operationLog = new OperationLog();
        // 设置操作用户、操作内容和时间戳
        operationLogService.saveOperationLog(operationLog);
    }
}

在上述代码中,@Pointcut定义了一个切点,它匹配了需要记录日志的方法。@AfterReturning是一个建议(advice),它在匹配的方法成功返回结果后执行,并记录日志。

确保替换com.yourpackage为你的实际包路径。

这个简单的例子展示了如何在Spring Boot应用中使用AOP来记录操作日志。根据实际需求,你可以进一步扩展这个例子,包括记录更详细的操作信息、使用数据库记录日志、使用异步日志记录等。

最后修改于:2024年09月06日 09:37

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日