卢松松网站模板,做移动网站优化优,网页设计与制作课程标准中职,公司核名查询官网[公共字段自动填充] 核心#xff1a;在切面类中捕获需要填充公共字段的 Mapper 方法#xff0c;方法上使用注解加以标识#xff0c;通过反射拿到需要填充的字段赋值方法#xff0c;进行赋值操作 1、自定义注解 AutoFill 
Target(ElementType.METHOD)
Retention(RetentionPo…[公共字段自动填充] 核心在切面类中捕获需要填充公共字段的 Mapper 方法方法上使用注解加以标识通过反射拿到需要填充的字段赋值方法进行赋值操作 1、自定义注解 AutoFill 
Target(ElementType.METHOD)
Retention(RetentionPolicy.RUNTIME)
public interface AutoFill {//数据库操作类型UPDATE INSERTOperationType value();
}2、枚举对象类 
public enum OperationType {/*** 更新操作*/UPDATE,/*** 插入操作*/INSERT
}3、自定义切面 AutoFillAspect 
Aspect
Component
Slf4j
public class AutoFillAspect {/*** 切入点*/Pointcut(execution(* com.sky.mapper.*.*(..))  annotation(com.sky.annotation.AutoFill))public void autoFillPointCut(){}/*** 前置通知在通知中进行公共字段的赋值*/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 now  LocalDateTime.now();Long currentId  BaseContext.getCurrentId();//就是获取修改人的id值不同项目不同的获取方法//根据当前不同的操作类型为对应的属性通过反射来赋值if(operationType  OperationType.INSERT){//为4个公共字段赋值try {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);//通过反射为对象属性赋值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(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);Method setUpdateUser  entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);//通过反射为对象属性赋值setUpdateTime.invoke(entity,now);setUpdateUser.invoke(entity,currentId);} catch (Exception e) {e.printStackTrace();}}}
}4、在Mapper接口的方法上加入 AutoFill 注解 
Mapper
public interface CategoryMapper {/*** 插入数据* param category*/AutoFill(value  OperationType.INSERT)void insert(Category category);/*** 根据id修改分类* param category*/AutoFill(value  OperationType.UPDATE)void update(Category category);}