1:先自定义一个注解

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Operation {
/**
* 模块类型
*/
int moduleType();
/**
* 具体操作
*/
int operateLogType() default 0;
/**
* 一级菜单
*/
int operateMenuType() default 0;
String operateContent() default "";
}

2:选择一个切面
@Slf4j
@Aspect
@Component
@AllArgsConstructor
@ApiModel(value = "操作日志切面")
public class OperationAspect {
//上面自定义的位置
@Pointcut("@annotation(com.wotao.crm.handler.Operation)")
public void logPointCut() {
}
@SneakyThrows
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) {
Object proceed = point.proceed();
try {
saveOperation(point);
} catch (Throwable throwable) {
log.info("日志记录异常,不影响正常业务", throwable);
}
return proceed;
}
private void saveOperation(JoinPoint joinPoint) {
// 获取方法上的注解
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Operation operation = method.getAnnotation(Operation.class);
//获取controller里面的参数值
Object[] args = joinPoint.getArgs();
if (operation != null) {
// 操作日志工厂类根据模块生成实例
OperationLog operationLog = OperationLogFactory.getInstance(Objects.requireNonNull(OperationLogEnum.get(operation.moduleType())));
// 批量操作需重复添加
operationLog.add(operation, args, new OperateLog());
}
}
}
@Component
@AllArgsConstructor
public class OperationAccount extends AbstractOperation {
@Override
public R add(Operation operation, Object[] args, OperateLog log) {
int operateLogType = operation.operateLogType();
if (operateLogType == OperateLogConst.EDIT) {
AccountDto dto = new AccountDto();
BeanUtils.copyProperties(args[0], dto);
Integer id = dto.getId();
if (id != null) {
log.setAssociationId(id.toString());
}
}
if (operateLogType == OperateLogConst.EDIT_STATUS) {
Integer accountId = 0;
Integer status = 0;
BeanUtils.copyProperties(args[0], accountId);
BeanUtils.copyProperties(args[1], status);
if (accountId != null && status != null) {
log.setAssociationId("改变" + accountId.toString() + "的状态为:" + status.toString());
}
}
return super.insertOperationLog(operation, log);
}
}
本文介绍了如何使用自定义注解`@Operation`标记方法,配合切面编程创建操作日志切面`OperationAspect`,并以`OperationAccount`为例展示如何捕获参数和执行特定操作。通过实例化`OperationLog`来记录模块类型、操作类型和相关参数。
1549

被折叠的 条评论
为什么被折叠?



