失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Spring Boot AOP 实现日志持久化

Spring Boot AOP 实现日志持久化

时间:2023-08-23 19:21:50

相关推荐

Spring Boot AOP 实现日志持久化

项目需要做日志管理,并持久化到数据库中

首先创建LogInterceptor,并在类的上方加上注解

1 @Aspect 2 @Component 3 public class LogInterceptor { 4

//注入repository 5@Autowired 6private LogRepositories logRepositories; 7 8@After(value = "execution(* com.bosch.WPCR.application.service.impl.*.*(..)))") //定义JointPoint为impl路径下的所有类的所有方法 9public void addLog(JoinPoint joinPoint) {10 TB_Log log = new TB_Log();11 12 MethodSignature signature = (MethodSignature) joinPoint.getSignature();13 String className = joinPoint.getTarget().getClass().getName(); //获取当前类名14 Method method = signature.getMethod();15 String methodName = method.getName(); //获取当前方法名16 17 if(!methodName.equals("loadUserByUsername")) { 当调用这个方法时,线程里还没有当前用户18 String userName = getCurrentUser().getUsername();19 log.setUserName(userName);20 }21 22 Object[] args = joinPoint.getArgs();23 String params = JSONObject.toJSON(args).toString();24 log.setOperationType(className + " || " + methodName);25 log.setParams(params);26 log.setDate(new Date());27 logRepositories.save(log);28}29 30public UserContext getCurrentUser() {31 UserContext userContext =(UserContext) SecurityContextHolder.getContext().getAuthentication().getPrincipal();32 //org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User)userDetails;33 return userContext;34}35 36 }

需要额外注意的是,最开始时,我直接在addLog方法里调用了userService的getCurrentUser()方法,同时这个方法也是定义的JointPoint之一,导致陷入了死循环之中

最后,附上数据库记录

如果觉得《Spring Boot AOP 实现日志持久化》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。