1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| package com.sky.aspect; import com.sky.annotation.AutoFill; import com.sky.context.BaseContext; import com.sky.enums.UpdateOrInsert; import com.sky.interceptor.JwtTokenAdminInterceptor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component;
import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.time.LocalDateTime;
@Slf4j @Component @Aspect public class AutoFillAspect { private final JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
public AutoFillAspect(JwtTokenAdminInterceptor jwtTokenAdminInterceptor) { this.jwtTokenAdminInterceptor = jwtTokenAdminInterceptor; }
@Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)") public void pointCut(){}
@Before("pointCut()") public void before(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); AutoFill annotation = method.getAnnotation(AutoFill.class); if(annotation == null){ String name = method.getName(); log.warn(" " +name + "方法上没有这个注解"); return; } UpdateOrInsert updateOrInsert = annotation.updateOrInsert();
Object[] args = joinPoint.getArgs(); Object object = args[0];
if(updateOrInsert == UpdateOrInsert.INSERT){ try { Method method1 = object.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class); Method method2 = object.getClass().getDeclaredMethod("setUpdateTime",LocalDateTime.class); Method method3 = object.getClass().getDeclaredMethod("setCreateUser",Long.class); Method method4 = object.getClass().getDeclaredMethod("setUpdateUser",Long.class);
method1.invoke(object,LocalDateTime.now()); method2.invoke(object,LocalDateTime.now()); method3.invoke(object, BaseContext.getCurrentId()); method4.invoke(object,BaseContext.getCurrentId());
} catch (Exception e) { throw new RuntimeException(e); }
}else{ try { Method method2 = object.getClass().getDeclaredMethod("setUpdateTime",LocalDateTime.class); Method method4 = object.getClass().getDeclaredMethod("setUpdateUser",Long.class); method2.invoke(object,LocalDateTime.now()); method4.invoke(object,BaseContext.getCurrentId()); } catch (Exception e) { throw new RuntimeException(e); } } } }
|