利用AOP+反射的技术 解决新增和修改时冗余字段

一、首先先定义一个枚举,枚举中定义两个属性

public enum AutoFillType {
    INSERT,UPDATE
}

二、定义一个注解,作为切点表达式的参数,同时通过注解里面的属性,来确定是新增还是修改

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    AutoFillType type();
}

三、定义一个切面类,用反射的方式解决类型不一致

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Before("@annotation(autoFill)")
    public void before(JoinPoint jp, AutoFill autoFill) throws Exception{
        log.info(jp.toString());
        Object[] args = jp.getArgs();
        Object arg = args[0];
        if(autoFill.type() == AutoFillType.INSERT) {
            Method setCreateTime = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            setCreateTime.invoke(arg,LocalDateTime.now());
            Method setUpdateTime = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            setUpdateTime.invoke(arg,LocalDateTime.now());
            Method setCreateUser = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            setCreateUser.invoke(arg, BaseContext.getCurrentId());
            Method setUpdateUser = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateUser.invoke(arg, BaseContext.getCurrentId());
        } else {
            Method setUpdateTime = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            setUpdateTime.invoke(arg,LocalDateTime.now());
            Method setUpdateUser = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateUser.invoke(arg, BaseContext.getCurrentId());
        }
    }
}

四、在mapper层方法上面,添加注解

@AutoFill(type = AutoFillType.INSERT)

@AutoFill(type = AutoFillType.UPDATE)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值