<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency>
package com.yg.domain.note;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @NAME: TODO:MyErrorAop
* @DATE: 2024/1/12
* /???\- NoBug
* @AUTHOR: Mr.zhou
*/
@Target(ElementType.METHOD)//可以用作于方法中
@Retention(RetentionPolicy.RUNTIME)//运行时使用
public @interface MyErrorAop {
}
编写Aop
package com.yg.common;
import com.yg.domain.SysYuangong;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* @NAME: TODO:MyErrorAop
* @DATE: 2024/1/12
* /???\- NoBug
* @AUTHOR: Mr.zhou
*/
@Aspect
@Component
public class MyErrorAop {
@Autowired
RedisTemplate redisTemplate;
// 扫描目标类
@Pointcut("@annotation(com.yg.domain.note.MyErrorAop)")
public void myValid(){
}
//TODO:创建切面:防止重复提交
@Around("myValid()")
public Object MyAop(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// 获取实体类对象
SysYuangong arg = (SysYuangong)proceedingJoinPoint.getArgs()[0];
// 判断校验字段是否为空
if (StringUtils.isBlank(arg.getToken())){
return ResultModel.error("没有有效token");
}
// 从redis获取字段
Boolean aBoolean = redisTemplate.hasKey(arg.getToken());
// 验证
if (!aBoolean){
return ResultModel.error("非法token 不能重复提交");
}
// 执行后续方法
Object proceed = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
// 删除校验字段
redisTemplate.delete(arg.getToken());
return proceed;
}
}