【spring】AOP、反射实现公共字段的自动填充,减少代码重复

概要

在实现公共字段自动填充,也就是在插入或者更新的时候为指定字段赋予指定的值,使用它的好处就是可以统一对这些字段进行处理,避免了重复代码。在上述的问题分析中,我们提到有四个公共字段,需要在新增/更新中进行赋值操作, 具体情况如下:

序号字段名含义数据类型操作类型
1create_time创建时间datetimeinsert
2create_user创建人idbigintinsert
3update_time修改时间datetimeinsert、update
4update_user修改人idbigintinsert、update

实现步骤

  1. 自定义注解 AutoFill,用于标识需要进行公共字段自动填充的方法
  2. 自定义切面类 AutoFillAspect,统一拦截加入了 AutoFill 注解的方法,通过反射为公共字段赋值
  3. 在 Mapper 的方法上加入 AutoFill 注解

技术点

枚举、注解、AOP、反射

代码实现

第一步:
在父模块下建一个annotation包
在这里插入图片描述

在AutoFill里面编写Java代码

/**
 * 自定义注解,用于标识某个方法需要进行功能字段自动填充处理
 */
@Target(ElementType.METHOD)//指定当前注解AutoFill会加在什么位置 是方法上
@Retention(RetentionPolicy.RUNTIME)//固定写法
public @interface AutoFill {
    //指定属性 数据库操作类型:UPDATE INSERT
    OperationType value();
}

其中OperationType已在别的common模块中定义

package com.sky.enumeration;

/**
 * 数据库操作类型
 */
public enum OperationType {

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

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

第二步:
自定义切面 AutoFillAspect

在父模块,创建aspect包
在这里插入图片描述在这里插入图片描述
给mapper里面的插入或修改的方法加上@AutoFill注解
在这里插入图片描述
在这里插入图片描述
之后再进行AutoFillAspect类里面编写前置通知(执行insert或update之前)给公共字段赋值

AutoFillAspect完整代码如下:

/**
 * 自定义切面,实现公共字段自动填充处理逻辑
 */
@Aspect  //切面注解
@Component  //交给bean管理的配置类
@Slf4j   //记录日志
public class AutoFillAspect {

    /**
     * 切入点
     */
    //扫描mapper下的所有类所有方法还要满足方法中加入了AutoFill的注解(插入和修改的方法,查询和删除是不需要的)
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointcut() {
    }

    /**
     * 前置通知,在通知中进行公共字段的赋值
     */
    @Before("autoFillPointcut()")//括号里面是指定切入点 也就是上面这个方法名
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行公共字段自动填充...");
        //1.获取到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
        OperationType operationType = autoFill.value();//获得数据库操作类型  是insert还是update类型


        //2.获取到当前被拦截的方法的参数--实体对象   因为是要为实体对象的公共属性赋值比如为实体的创建时间赋值
        Object[] args = joinPoint.getArgs();//获取方法上所有的参数
        if (args == null || args.length == 0) {//没有参数的情况
            return;
        }
        Object entity = args[0];//实体对象作为第一个参数的约定

        //3.准备赋值的数据:   时间和当前登录用户的id
        LocalDateTime now = LocalDateTime.now();//时间
        Long currentId = BaseContext.getCurrentId();//当前登录用户的id

        //4.根据当前不同的操作类型,为对应的属性通过反射来赋值
        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);

                //通过反射为对象属性赋值
                setCreateTime.invoke(entity, now);
                setCreateUser.invoke(entity,currentId);
                setUpdateTime.invoke(entity,now);
                setUpdateUser.invoke(entity,currentId);
            } catch (Exception ex) {
                log.error("公共字段自动填充失败:{}", ex.getMessage());
            }

        }else if (operationType==OperationType.UPDATE){
            //为2个公共字段赋值
            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,now);
                setUpdateUser.invoke(entity,currentId);
            } catch (Exception ex) {
                log.error("公共字段自动填充失败:{}", ex.getMessage());
            }
        }
    }
}

第三步:删掉之前impl包里面的公共属性赋值的代码,因为已经用上边的切面形式赋值了
在这里插入图片描述

测试

通过观察控制台输出的SQL来确定公共字段填充是否完成
在这里插入图片描述
话不多说,成功完成该功能!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@¥文竹¥

你的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值