自定义注解之公共字段填充

通过AOP实现

 //自定义注解,用于标识某个方法需要进行功能字段自动填充处理
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    //数据库操作类型:UPDATE INSERT
    OperationType value();
}

创建aspect包,创建类AutoFillAspect,代码如下:

//自定义切面,实现公共字段自动填充处理逻辑
@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("开始进行公共字段自动填充...");
    }
}

切入点:对哪些类的哪些方法进行拦截。@Pointcut里面写的是对哪些方法进行拦截,要满足2点:①必须是mapper下的所有类的方法,②还要有AutoFill这个注解。

获取到当前被拦截的方法的参数--实体对象(比如传入的参数是员工还是菜品还是其它的)

Object[] args = joinPoint.getArgs(); //获得了方法所有的参数
if(args == null || args.length==0 ){ //没有参数
     return;
}
Object entity = args[0];//现在约定实体放在第1个位置,传入实体可能不同所以用Object

准备赋值的数据(给公共字段赋值的数据,比如时间就是系统时间,用户ID是从ThreadLocal获取)

根据当前不同的操作类型,为对应的属性通过反射来赋值

  LocalDateTime now = LocalDateTime.now();
  Long currentId = BaseContext.getCurrentId();
  if(operationType == OperationType.INSERT){
      //为4个公共字段赋值
      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);
          //4.根据当前不同的操作类型,为对应的属性通过反射来赋值
          setCreateTime.invoke(entity,now);
          setCreateUser.invoke(entity,currentId);
          setUpdateTime.invoke(entity,now);
          setUpdateUser.invoke(entity,currentId);
      }catch (Exception e){
          e.printStackTrace();
      }
  }else if(operationType == OperationType.UPDATE){
      try {
          //为2个公共字段赋值
          Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
          Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
          //4.根据当前不同的操作类型,为对应的属性通过反射来赋值
          setUpdateTime.invoke(entity, now);
          setUpdateUser.invoke(entity, currentId);
      }catch (Exception e){
          e.printStackTrace();
      }
  }
  }
posted @ 2025-03-10 19:55  ALONN  阅读(44)  评论(0)    收藏  举报