背景:日常开发中,对mysql基础数据表进行设计时,几乎每个表都要有创建人创建时间更新人更新时间这四个标准字段,那么每次进行curd的时候,如果每次都要对此4个字段进行赋值,代码重复率会非常高,而且开发效率会降低,一旦漏掉操作容易导致bug。
方案:在controller方法上通过自定义注解实现aop切面。
步骤:
1、定义基类:
@Data
public class BaseEntity implements Serializable {
private Long creatorId;
private String creatorName;
private Date createTime;
private Long updaterId;
private String updaterName;
private Date updateTime;
}2、定义DTO:
@Data
public class Goods extends BaseEntity {
private String name;
}3、自定义切面注解:
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BaseInfoAnnotation {
OperateTypeEnum value();
}4、操作类型枚举:
public enum OperateTypeEnum {
ADD,
DELETE,
UPDATE;
}5、自定义 aop 操作:
public class BaseInfoAop {
@Pointcut("@annotation(com.xx.aop.BaseInfoAnnotation))")
public void setBaseInfo(){}
@Around("setBaseInfo()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object res = null;
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
MetaInfoAnnotation annotation = signature.getMethod().getAnnotation(BaseInfoAnnotation.class);
OperateTypeEnum value = annotation.value();
Object[] args = joinPoint.getArgs();
if (args.length > 0) {
BaseInfo arg = (BaseInfo) args[0];
Date now = new Date();
UserInfo user = SessionUtil.getUser().getUserInfo();
Long userId = user.getUserId();
String userName = user.getRealName();
if (value == OperateTypeEnum.ADD) {
arg.setCreatorId(userId);
arg.setCreatorName(userName);
arg.setCreateTime(now);
arg.setUpdaterId(userId);
arg.setUpdaterName(userName);
arg.setUpdateTime(new Date());
} else if (value == OperateTypeEnum.UPDATE || value == OperateTypeEnum.DELETE) {
arg.setUpdaterId(userId);
arg.setUpdaterName(userName);
arg.setUpdateTime(new Date());
}
}
return joinPoint.proceed(args);
}
}6、定义Controller
@RestController
@RequestMapping("/student")
public class StudentsController {
@BaseInfoAnnotation(value = OperateTypeEnum.ADD)
@PostMapping("")
public ResponseBean save(@RequestBody Students students){
try {
service.add(students);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return new ResponseBean(true, "保存成功", ResponseCode.SUCCESS);
}版权声明:本文为m0_37611361原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。