苍穹Day2-3

swagger

在controller接口方法上加上注解:

1
@ApiOperation("接口名")

公共字段自动填充 ——AOP 反射 注解 枚举

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(); //通过注解的枚举得到方法的类型

//要获取这个方法的参数,也要通过joinpoint获得
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()); //LocalThread
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);
}
}
}
}