关于java:Aop实现自动填充字段值

5次阅读

共计 2428 个字符,预计需要花费 7 分钟才能阅读完成。

需要:主动填充更新工夫创立工夫,创立用户和更新用户。

自定义注解:OperationType 类是一个枚举

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

OperationType 枚举类

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

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

/**
 * 插入操作
 */
    INSERT

}

应用 aop 并且申明一个事务

package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {@Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
public void pt() {}

@Before("pt()")
public void autoFill(JoinPoint joinPoint) {
    // 获取签名对象
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    // 获取办法上注解
    AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
    OperationType value = annotation.value();
    // 解析注解是减少还是更新
    Object[] args = joinPoint.getArgs();
    if (Objects.isNull(args) || args.length == 0) {return;}
    Object target = args[0];
    LocalDateTime now = LocalDateTime.now();
    Long currentId = BaseContext.getCurrentId();
    Class<?> clazz = target.getClass();
    if (value == OperationType.INSERT) {
        try {Method setCreateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUserMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            setCreateTimeMethod.invoke(target,now);
            setCreateUserMethod.invoke(target,currentId);
            autoFillUpdateMethod(now,currentId,clazz,target);
        } catch (Exception e) {e.printStackTrace();
        }
    } else if (value == OperationType.UPDATE) {
        try {autoFillUpdateMethod(now,currentId,clazz,target);
        } catch (Exception e) {e.printStackTrace();
        }
    }
}

private void autoFillUpdateMethod(LocalDateTime now, Long id, Class<?> clazz, Object target) throws Exception {Method setUpdateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
    Method setUpdateUserMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
    setUpdateTimeMethod.invoke(target,now);
    setUpdateUserMethod.invoke(target,id);
}

}

正文完
 0