一.自定义注解的声明
@Target(ElementType.METHOD) // @Target注解用来标注生效范围,
// 这里标注的是生效在方法上,还可以是对象,元素等
@Retention(RetentionPolicy.RUNTIME) // @Retention注解用来标注生效时间,
// 这里是运行时生效
public @interface LoginCheck { //@interface用来声明一个注解,我这里就声明了一个LoginCheck注解
//这里面还可以写元素、变量什么的,
//比如 String token();
//写法类似于抽象方法
}
二.自定义注解可执行方法
主要的我就用了两个,一个before,一个around
1)before
@Before("loginCheck()")
public void checkLogin( ){//在调用接口前执行
log.info("aop发挥了作用");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
Object o = redisUtil.get(token);
if (o == null) {
System.out.println("在执行该操作前请先登录");
throw new BaseException(ExceptionCode.EXCEPTION_NOTLOGIN);
}
}
2)around
@Around("loginCheck()")
public Object checkLogin1(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {//在调用接口的途中执行
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
Object o = redisUtil.get(token);
if (o == null) {
System.out.println("在执行该操作前请先登录");
throw new BaseException(ExceptionCode.EXCEPTION_NOTLOGIN);
}else{
return proceedingJoinPoint.proceed();
}
}
完整代码
@Aspect//定义一个切面
@Component
@Slf4j
public class LoginCheckAOP {
@Autowired
RedisUtil redisUtil;
@Pointcut("@annotation(com.example.login.Annotation.LoginCheck)") //绑定注解
private void loginCheck(){ }
@Before("loginCheck()")
public void checkLogin( ){//在调用接口前执行
log.info("aop发挥了作用");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
Object o = redisUtil.get(token);
if (o == null) {
System.out.println("在执行该操作前请先登录");
throw new BaseException(ExceptionCode.EXCEPTION_NOTLOGIN);
}
}
@Around("loginCheck()")
public Object checkLogin1(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {//在调用接口的途中执行
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
Object o = redisUtil.get(token);
if (o == null) {
System.out.println("在执行该操作前请先登录");
throw new BaseException(ExceptionCode.EXCEPTION_NOTLOGIN);
}else{
return proceedingJoinPoint.proceed();
}
}
}
三.使用
只需和其他注解一样写在方法前即可
@LoginCheck
@PostMapping("/findrelation")
BaseResponse findRelation(@RequestBody BlogVo blogVo){
BaseResponse baseResponse = new BaseResponse(StatusCode.Success);
baseResponse.setData(blogAttendService.findRelation(blogVo.getBlogId(),blogVo.getUserId()));
return baseResponse;
}
调用接口得结果