本文实现insert方法自动给第一个参数的实体或者集合内的实体进行ID赋值。
用的技术主要是Spring AOP 和 reflect 反射,具体原理可自行百度
1.引入依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.22.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
</dependency>
2.建实体
import lombok.Data;
@Data
public class Student {
private String id;
private String name;
}
3.Controller
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/aop/test")
public class AopTestController {
@PostMapping("/insert")
public String insert(@RequestBody List<Student> stus){
return stus.toString();
}
}
4.写切面
因为要实现的是插入数据之前进行ID赋值,所以这里切点是insert开头的方法,以前置通知,拿到第一个参数,进行赋值
import cn.hutool.core.util.IdUtil;
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.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
@Aspect
@Component
public class InsertAop {
@Pointcut("execution(* insert*(..))")
public void insertPointcut(){
}
@Before("insertPointcut()")
public void before(JoinPoint jp) throws NoSuchFieldException, IllegalAccessException {
Object[] args = jp.getArgs();
Object firstArg = args[0];
if(firstArg instanceof Collection){
List<Object> list = (List<Object>)firstArg;
for (Object obj : list) {
Class<?> aClass = obj.getClass();
Field id = aClass.getDeclaredField("id");
id.setAccessible(true);
id.set(obj, IdUtil.simpleUUID());
}
}else {
Class<?> aClass = firstArg.getClass();
Field id = aClass.getDeclaredField("id");
id.setAccessible(true);
id.set(firstArg, IdUtil.simpleUUID());
}
}
}
5.PostMan 测试
路径:127.0.0.1:8081/aop/test/insert
参数:
[
{
"name": "zs"
},
{
"name": "ls"
},
{
"name": "ww"
}
]
结果
[Student(id=b554532835d443f1b2c9eaf3472d1ba6, name=zs), Student(id=57c4e8a9787a4620acd34aa819d6f2a4, name=ls), Student(id=461d40f2bfc04e069225c1a525cb8921, name=ww)]