日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

通過AOP切面實現公共字段的自動填充

作者:Hacker_Hacker007 更新時間: 2024-02-17 編程語言

以create_time、update_time、create_user、update_user字段為例

實現步驟:

第一步:創建一個枚舉

public enum OperationType {

? ? /**
? ? ?* 更新操作
? ? ?*/
? ? UPDATE,

? ? /**
? ? ?* 插入操作
? ? ?*/
? ? INSERT
}

第二步:自定義一個注解

/**
?* 自定義注解,用于標識某個方法需要進行功能字段自動填充處理
?*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
? ? //數據庫操作類型:UPDATE INSERT
? ? OperationType value();
}

第三步:在需要填充的Mapper層的方法上加上相應的注解,eg:

第四步:通過aop使得添加的注解生效

@Aspect
@Component
public class AutofillAspect {

? ? @Before("execution(* com.sky.mapper.*.*(..)) && @annotation(autoFill)")
? ? public void autoFill(JoinPoint joinPoint, AutoFill autoFill){
? ? ? ? log.info("開始自動填充公共字段值");

? ? ? ? //獲取Mapper方法的參數:entity對象
? ? ? ? Object[] args = joinPoint.getArgs();
? ? ? ? if (args == null || args.length == 0) {
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? Object entity = args[0];

? ? ? ? //準備要賦的值
? ? ? ? LocalDateTime now = LocalDateTime.now();
? ? ? ? Long currentUser = BaseContext.getCurrentId();

? ? ? ? //判斷操作的類型
? ? ? ? Class<?> clazz = entity.getClass();
? ? ? ? if (autoFill.value() == OperationType.INSERT) {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? //是新增操作:獲取setCreateTime、setUpdateTime、setCreateUser、setUpdateUser四個方法
? ? ? ? ? ? ? ? Method setCreateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
? ? ? ? ? ? ? ? Method setUpdateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
? ? ? ? ? ? ? ? Method setCreatorMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
? ? ? ? ? ? ? ? Method setUpdatorMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

? ? ? ? ? ? ? ? //使用反射調用entity的對應方法,給屬性賦值
? ? ? ? ? ? ? ? setCreateTimeMethod.invoke(entity, now);
? ? ? ? ? ? ? ? setUpdateTimeMethod.invoke(entity, now);
? ? ? ? ? ? ? ? setCreatorMethod.invoke(entity, currentUser);
? ? ? ? ? ? ? ? setUpdatorMethod.invoke(entity, currentUser);
? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? }
? ? ? ? }else{
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? //是修改操作:獲取setUpdateTime、setUpdateUser兩個方法
? ? ? ? ? ? ? ? Method setUpdateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
? ? ? ? ? ? ? ? Method setUpdatorMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
? ? ? ? ? ? ? ? //使用反射調用entity的對應方法,給屬性賦值
? ? ? ? ? ? ? ? setUpdateTimeMethod.invoke(entity, now);
? ? ? ? ? ? ? ? setUpdatorMethod.invoke(entity, currentUser);
? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? }
? ? ? ? }
? ? }
}

最后就能夠正常使用了

原文鏈接:https://blog.csdn.net/Hacker_Hacker007/article/details/136127410

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新