实现步骤
自定义注解,以AutoFill为例
//指定该注解只能用在方法上 @Target(ElementType.METHOD) //表示注解不仅会被编译到字节码中,而且在运行时也可以通过反射获取 @Retention(RetentionPolicy.RUNTIME) public @interface AutoFill { // 指定操作类型 OperationType value(); }
自定义切面实现公共字段自动填充功能
的方式
/**
* 自定义切面实现公共字段自动填充功能
*/
@Aspect
@Component
@Slf4j
public class autoFillAspect {
/**
* 切入点
*/
@Pointcut("execution(public * com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill))")
public void autoFillPointcut(){}
/**
* 前置通知
* @param joinPoint
*/
@Before("autoFillPointcut()")
public void autoFill(JoinPoint joinPoint){
log.info("开始自动填充...");
// 获取当前数据库的操作类型
MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
OperationType operationType = autoFill.value();
// 获取当前方法的参数
Object[] args = joinPoint.getArgs();
if(args == null || args.length == 0) return;
Object entity = args[0]; //默认要处理的对象放在第一位
// 准备赋值的参数
LocalDateTime nowTime = LocalDateTime.now();
long currentId = BaseContext.getCurrentId();
// 根据操作类型的不同为参数赋值
if(operationType == OperationType.INSERT){
try {
// 利用反射获取set方法
Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
// 调用set方法
setCreateTime.invoke(entity,nowTime);
setUpdateTime.invoke(entity,nowTime);
setCreateUser.invoke(entity,currentId);
setUpdateUser.invoke(entity,currentId);
} catch (Exception e) {
throw new RuntimeException(e);
}
}else {
try {
// 利用反射获取set方法
Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
// 调用set方法
setUpdateTime.invoke(entity,nowTime);
setUpdateUser.invoke(entity,currentId);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}