概要
在常用的编辑信息时需要自动填充公共字段,比如更新时间字段和修改人字段等等
整体架构流程
自定义注解AutoFill,用于表示需要进行公共字段自动填充的方法
自定义切面类AutoFillAspect,同一拦截加入了AutoFill注解的方法
在Mapper方法上加上AutoFill
具体步骤
1.创建一个
annotation包,在包下创建一个AutoFill注解类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
OperationType value();
}
OperationType是一个枚举类
代码如下
public enum OperationType {
/**
* 更新操作
*/
UPDATE,
/**
* 插入操作
*/
INSERT
}
2.创建一个包
aspect ,在包下创建AutoFillAspect类
这是一个切面类,作用是拦截mapper里面所有加了@AutoFill注解的方法
@Aspect //切面类
@Component
@Slf4j
public class AutoFillAspect {
/*切入点
* */
//锁定了mapper类下面所有的方法 同时还要满足方法上加入了@AutoFill注解
@Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
public void autoFillPointCut() { //annotation注解
}
@Before("autoFillPointCut()")
public void autoFill(JoinPoint joinpoint) {
log.info("开始进行公共字段填充");
}
}
3.然后在mapper层类的方法上加上AutoFill注解
@AutoFill(value = OperationType.INSERT)
这是一个mapper层下的新增员工接口和更新员工接口
@AutoFill(value = OperationType.INSERT)
int insert(Employee employee);
@AutoFill(value = OperationType.UPDATE)
void update(Employee employee);
4.现在开始编写 切面类AutoFillAspect , autoFill方法里
的代码
要判断加上@AutoFill注解的方法是更新操作还是新增操作
如果是新增操作,则需要
更新这4个字段setCreateTime setCreateUser setUpdateTime setUpdateUser
如果是更新操作,则需要
更新这2个字段 setUpdateTime setUpdateUser
具体代码如下:
public void autoFill(JoinPoint joinpoint) {
log.info("开始进行公共字段填充");
//获取当前被拦截的方法上的数据库操作类型
MethodSignature signature = (MethodSignature) joinpoint.getSignature(); //方法签名对象
AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
OperationType operationType = annotation.value();//获得数据库操作类型
//获取到当前被拦截的方法的参数
Object[] args = joinpoint.getArgs();
if (args == null || args.length == 0) {
return;
}
Object entity = args[0];
//准备需要赋值的数据
LocalDateTime now = LocalDateTime.now();
Long currentId = BaseContext.getCurrentId();
//根据不同的操作类型,为对应的属性通过反射赋值
if (operationType==OperationType.INSERT){
//4个字段
try {
Method setCreateTime = entity.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
Method setCreateUser = entity.getClass().getDeclaredMethod("setCreateUser", Long.class);
Method setUpdateTime = entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
Method setUpdateUser = entity.getClass().getDeclaredMethod("setUpdateUser", Long.class);
//通过反射为对象赋值
setCreateTime.invoke(entity,now);
setCreateUser.invoke(entity,currentId);
setUpdateTime.invoke(entity,now);
setUpdateUser.invoke(entity,currentId);
} catch (Exception e) {
e.printStackTrace();
}
}
else if (operationType==OperationType.UPDATE){
//2个字段
try {
Method setUpdateTime = entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
Method setUpdateUser = entity.getClass().getDeclaredMethod("setUpdateUser", Long.class);
//通过反射为对象赋值
setUpdateTime.invoke(entity,now);
setUpdateUser.invoke(entity,currentId);
} catch (Exception e) {
e.printStackTrace();
}
}
}