自定义注解
公共字段有create_time,update_time,create_time,update_time。这四个字段变动在insert或者update操作时
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
OperrationType value();// OperrationType为枚举类型,枚举insert,update两种操作
}
@Component
@Slf4j
@Aspect
public class AutoFillAspect {
@Pointcut("@annotation(AutoFill)")
public void pointCut(){}
@Before("pointCut()")
public void autoFill(JoinPoint joinPoint){
MethodSignature signature =(MethodSignature) joinPoint.getSignature();
String name = signature.getName();
AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
OperrationType value = annotation.value();
Object[] args = joinPoint.getArgs();
Object arg = args[0];
LocalDateTime now = LocalDateTime.now();
if(value.equals(OperrationType.INSERT)){
try {
Method setCreateTime = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
//...
setCreateTime.invoke(arg,now);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
else System.out.println("这是更新");
}
}
反射常见作用:
获取类的类名。父类,接口
创建类的实例对象
动态调用方法
访问属性
获取方法返回值类型,参数类型