公共字段自动填充

文章介绍了如何使用Java的注解(如@AutoFill)和AspectJ实现,当执行insert或update操作时,自动设置create_time或update_time字段,利用Reflection库动态获取和修改对象的方法。
摘要由CSDN通过智能技术生成

自定义注解
公共字段有create_time,update_time,create_time,update_time。这四个字段变动在insert或者update操作时

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    OperrationType value();// OperrationType为枚举类型,枚举insert,update两种操作
}
@Component
@Slf4j
@Aspect
public class AutoFillAspect {
    @Pointcut("@annotation(AutoFill)")
    public void pointCut(){}
    @Before("pointCut()")
    public void autoFill(JoinPoint joinPoint){
     MethodSignature signature =(MethodSignature) joinPoint.getSignature();
        String name = signature.getName();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperrationType value = annotation.value();
        Object[] args = joinPoint.getArgs();
        Object arg = args[0];
        LocalDateTime now = LocalDateTime.now();
        if(value.equals(OperrationType.INSERT)){
            try {
                Method setCreateTime = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
               //...
                setCreateTime.invoke(arg,now);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

        }
        else System.out.println("这是更新");
    }
}

反射常见作用:
获取类的类名。父类,接口
创建类的实例对象
动态调用方法
访问属性
获取方法返回值类型,参数类型

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值