使用注解+反射实现自动填充

发布于 更新于 174 字 2 分钟阅读

#使用注解+反射实现自动填充

#使用场景介绍


不同操作需要频繁对同一个对象进行相同操作时,可以使用自动填充简化代码,如:

  • 更新或插入一条数据时,需要设置 update_timeupdate_user,项目中会有多个业务需要进行插入或更新数据,所有使用自动填充非常合适

#前置知识


#代码实现


#定义注解

在定义注解前,可以根据需要,添加如下枚举类:

Java
/**  
 * 数据库操作类型  
 */  
public enum OperationType {  
  
    /**  
     * 更新操作  
     */  
    UPDATE,  
  
    /**  
     * 插入操作  
     */  
    INSERT  
  
}

定义注解:

Java
/**
 * Author: Administrator
 * CreateTime: 2024/8/30
 * Project: sky-take-out
 * 自动填充
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    /**
     * 数据库操作类型
     */
    OperationType value();
}

#切片类

Java
/**
 * 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)

zxb的博客

评论

还没有评论,来说点什么吧。

评论经发布者审核后公开
46 篇文档

文档树

6 个章节

本文目录

搜索文档

输入关键词,立即搜索当前分享。