1. 问题分析

2. 实现思路

3. 代码实现
3.1. 自定义注解
/**
* 自定义注解, 用于标识哪个方法进行自动填充字段
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
// 数据库操作类型, 插入、更新
OperationType value();
}
3.2. 定义切面
@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 value = autoFill.value();
// 获取方法参数 --实体对象
Object[] args = joinPoint.getArgs();
// 判断参数数组是否为空
if(args == null || args.length == 0){
return;
}
// 约定第一个参数为实体对象
Object object = args[0];
// 获取填充的参数值
LocalDateTime now = LocalDateTime.now();
Long currentId = BaseContext.getCurrentId();
// 根据不同的操作类型, 通过反射进行字段填充
// 若为插入操作
if(value == OperationType.INSERT){
try {
Method setCreateTime = object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
Method setCreateUser = object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
Method setUpdateTime = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
Method setUpdateUser = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
// 通过反射为对象属性赋值
setCreateTime.invoke(object, now);
setCreateUser.invoke(object,currentId);
setUpdateTime.invoke(object, now);
setUpdateUser.invoke(object, currentId);
} catch (Exception e) {
e.printStackTrace();
}
} else if (value == OperationType.UPDATE) {
try {
Method setUpdateTime = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
Method setUpdateUser = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
// 通过反射为对象属性赋值
setUpdateTime.invoke(object, now);
setUpdateUser.invoke(object, currentId);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
3.3. 在相应的方法加入注解