一、涉及技术点
技术点:AOP 注解 反射 枚举
自定义注解+AOP处理公共字段问题
二、实现步骤——自定义注解
自定义注解AutoFill,标识需要进行公共字段自动填充的方法
/**
* 自定义注解:用于标识某个方法需要进行公共字段自动填充处理
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
//数据库操作类型:UPDATE INSERT
OperationType value();
}
三、实现步骤——自定义切面类
自定义切面类AutoFillAspect,统一拦截加入了AutoFillAspect自定义注解的方法,并通过反射为公共字段赋值
1.定义切入点和通知
/**
* 切入点
*/
@Pointcut("execution(* com.sky.mapper.*.*(..)) && " +
"@annotation(com.sky.annotation.AutoFill)")
public void autoFillPointCut(){
}
/**
* 前置通知:为公共字段赋值
*/
@Before("autoFillPointCut()")
public void autoFill(JoinPoint joinPoint) {
log.info("开始进行公共字段自动填充...");
}
2.获取数据
//获取当前方法上拦截的数据库操作类型
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 localDateTime = LocalDateTime.now();
Long currentId = BaseContext.getCurrentId();
3.通过反射为公共字段赋值
//根据不同的操作类型,通过反射为对应的属性赋值
if (operationType == OperationType.INSERT) {
//为四个公共字段赋值
try {
Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
//通过反射为对象赋值
setCreateTime.invoke(entity, localDateTime);
setCreateUser.invoke(entity, currentId);
setUpdateTime.invoke(entity, localDateTime);
setUpdateUser.invoke(entity, currentId);
} catch (Exception e) {
e.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);
//通过反射为对象属性赋值
setUpdateTime.invoke(entity,localDateTime);
setUpdateUser.invoke(entity,currentId);
} catch (Exception e) {
e.printStackTrace();
}
}
四、实现步骤——在Mapper方法添加自定义注解
在mapper的方法上加入自定义注解AutoFill
@Insert
@AutoFill(OperationType.INSERT)
void insert(Employee employee);