Spring Boot AOP 实现日志持久化
项目需要做日志管理,并持久化到数据库中
首先创建LogInterceptor,并在类的上方加上注解
1 @Aspect 2 @Component 3 public class LogInterceptor { 4
//注入repository 5 @Autowired 6 private LogRepositories logRepositories; 7 8 @After(value = "execution(* com.bosch.WPCR.application.service.impl.*.*(..)))") //定义JointPoint为impl路径下的所有类的所有方法 9 public 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 30 public 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之一,导致陷入了死循环之中
最后,附上数据库记录