公共字段自动填充

1. 问题分析

2. 实现思路

3. 代码实现

3.1. 自定义注解

/**
 * 自定义注解, 用于标识哪个方法进行自动填充字段
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    // 数据库操作类型, 插入、更新
    OperationType value();
}

3.2. 定义切面

@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 value = autoFill.value();
        // 获取方法参数 --实体对象
        Object[] args = joinPoint.getArgs();
        // 判断参数数组是否为空
        if(args == null || args.length == 0){
            return;
        }
        // 约定第一个参数为实体对象
        Object object = args[0];
        // 获取填充的参数值
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        // 根据不同的操作类型, 通过反射进行字段填充
        // 若为插入操作
        if(value == OperationType.INSERT){
            try {
                Method setCreateTime = object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateTime = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                // 通过反射为对象属性赋值
                setCreateTime.invoke(object, now);
                setCreateUser.invoke(object,currentId);
                setUpdateTime.invoke(object, now);
                setUpdateUser.invoke(object, currentId);

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (value == OperationType.UPDATE) {
            try {
                Method setUpdateTime = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                // 通过反射为对象属性赋值
                setUpdateTime.invoke(object, now);
                setUpdateUser.invoke(object, currentId);
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }
}

3.3. 在相应的方法加入注解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值