1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| @Aspect @Component @Slf4j public class AutoFillAspect {
@Pointcut("execution(* com.work.mapper.*.*(..)) && @annotation(com.work.annotation.AutoFill)") public void autoFillPointCut() {}
@Before("autoFillPointCut()") public void autoFill(JoinPoint joinPoint) { log.info("开始进行公共字段的填充");
MethodSignature signature = (MethodSignature) joinPoint.getSignature(); AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class); OperationType operationType = autoFill.value();
Object[] args = joinPoint.getArgs(); if (args == null || args.length == 0){ return; } Object entity = args[0];
LocalDateTime now = LocalDateTime.now(); Long currentId = BaseContext.getCurrentId();
if (operationType == OperationType.INSERT){ try { entity.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class).invoke(entity, now); entity.getClass().getDeclaredMethod("setCreateUser", Long.class).invoke(entity,currentId); entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(entity, now); entity.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(entity,currentId); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); }
}else if(operationType == OperationType.UPDATE){ try { entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(entity, now); entity.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(entity,currentId); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } }
}
|