Spring AOP 实现《自动自动填充Entity》
定义注解
AutoFill.java
/** * 自定义注解,实现自动填填充功能 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AutoFill { OperationType value() default OperationType.INSERT; }
定义AOP
AutoFillAspect.java
@Aspect @Component @Slf4j public class AutoFillAspect { /** * 定义切点 */ @Pointcut(value = "execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.aspect.annotation.AutoFill)") public void autoFillPointCut(){} @Before("autoFillPointCut()") public void autoFill(JoinPoint joinPoint){ log.info("开始自动填充autoFill"); //获取到当前被拦截的方法上的数据库操作类型 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //方法签名对象 AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);//获取方法上的注解对象 OperationType operationType = annotation.value();//获取注解上自定义的操作类型 //获取注解上的参数 Object[] args = joinPoint.getArgs(); if(args == null || args.length == 0) return ; Object entity = args[0] ; LocalDateTime nowTime = LocalDateTime.now(); //当前时间 Long currentId = BaseContext.getCurrentId(); // 当前登录用户Id if(operationType == OperationType.INSERT){ //插入操作 try { Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class); Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class); Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class); Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class); //通过反射赋值 if(setCreateTime!=null){ setCreateTime.invoke(entity,nowTime); } if(setUpdateTime!=null){ setUpdateTime.invoke(entity,nowTime); } if(setUpdateUser!=null){ setUpdateUser.invoke(entity,currentId); } if(setCreateUser!=null){ setCreateUser.invoke(entity,currentId); } }catch (Exception ex){ ex.printStackTrace(); } }else if(operationType == OperationType.UPDATE){ try { Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class); Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class); if(setUpdateTime!=null){ setUpdateTime.invoke(entity,nowTime); } if(setUpdateUser!=null){ setUpdateUser.invoke(entity,currentId); } }catch (Exception ex){ ex.printStackTrace(); } } } }
枚举
/** * 数据库操作类型 */ public enum OperationType { /** * 更新操作 */ UPDATE, /** * 插入操作 */ INSERT }
本文来自博客园,作者:一个小笨蛋,转载请注明原文链接:https://www.cnblogs.com/paylove/p/18101456
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步