一、首先先定义一个枚举,枚举中定义两个属性
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)