不同操作需要频繁对同一个对象进行相同操作时,可以使用自动填充简化代码,如:
在定义注解前,可以根据需要,添加如下枚举类:
/**
* 数据库操作类型
*/
public enum OperationType {
/**
* 更新操作
*/
UPDATE,
/**
* 插入操作
*/
INSERT
}
定义注解:
/**
* Author: Administrator
* CreateTime: 2024/8/30
* Project: sky-take-out
* 自动填充
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
/**
* 数据库操作类型
*/
OperationType value();
}
/**
* Author: Administrator
* CreateTime: 2024/8/30
* Project: sky-take-out
*/
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
/**
* 切入点
*/
@Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.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 time = LocalDateTime.now();
Long empId = BaseContext.getCurrentId();
if (operationType == OperationType.INSERT) {
// 当前执行的操作是插入操作,为4个字段赋值
try {
// 获得 set 方法对象 --- Method
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);
// 通过反射调用目标的方法
setCreateTime.invoke(entity, time);
setUpdateTime.invoke(entity, time);
setCreateUser.invoke(entity, empId);
setUpdateUser.invoke(entity, empId);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
log.error("自动填充失败: {}", e.getMessage());
}
} else {
// 当前执行的操作不是插入操作,为2个字段赋值
try {
// 获得 set 方法对象 --- Method
Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
// 通过反射调用目标的方法
setUpdateTime.invoke(entity, time);
setUpdateUser.invoke(entity, empId);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
log.error("自动填充失败: {}", e.getMessage());
}
}
}
}
最后在需要的类上添加注解:@AutoFill(OperationType.xxx)
暂无评论,欢迎第一个留言。
评论