学无先后,达者为师

网站首页 编程语言 正文

通过AOP切面实现公共字段的自动填充

作者:Hacker_Hacker007 更新时间: 2024-02-17 编程语言

以create_time、update_time、create_user、update_user字段为例

实现步骤:

第一步:创建一个枚举

public enum OperationType {

    /**
     * 更新操作
     */
    UPDATE,

    /**
     * 插入操作
     */
    INSERT
}

第二步:自定义一个注解

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

第三步:在需要填充的Mapper层的方法上加上相应的注解,eg:

第四步:通过aop使得添加的注解生效

@Aspect
@Component
public class AutofillAspect {

    @Before("execution(* com.sky.mapper.*.*(..)) && @annotation(autoFill)")
    public void autoFill(JoinPoint joinPoint, AutoFill autoFill){
        log.info("开始自动填充公共字段值");

        //获取Mapper方法的参数:entity对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];

        //准备要赋的值
        LocalDateTime now = LocalDateTime.now();
        Long currentUser = BaseContext.getCurrentId();

        //判断操作的类型
        Class<?> clazz = entity.getClass();
        if (autoFill.value() == OperationType.INSERT) {
            try {
                //是新增操作:获取setCreateTime、setUpdateTime、setCreateUser、setUpdateUser四个方法
                Method setCreateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreatorMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdatorMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                //使用反射调用entity的对应方法,给属性赋值
                setCreateTimeMethod.invoke(entity, now);
                setUpdateTimeMethod.invoke(entity, now);
                setCreatorMethod.invoke(entity, currentUser);
                setUpdatorMethod.invoke(entity, currentUser);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            try {
                //是修改操作:获取setUpdateTime、setUpdateUser两个方法
                Method setUpdateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdatorMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                //使用反射调用entity的对应方法,给属性赋值
                setUpdateTimeMethod.invoke(entity, now);
                setUpdatorMethod.invoke(entity, currentUser);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

最后就能够正常使用了

原文链接:https://blog.csdn.net/Hacker_Hacker007/article/details/136127410

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新