Aop实现自动填充字段值

需求:自动填充更新时间创建时间,创建用户和更新用户。

自定义注解: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);
}

}

你可能感兴趣的:(javaspring)