1.在 pom.xml 中引入响应的依赖模块;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.新建一个自定义注解类,加了这个注解的方法就表示切入点,即目标方法;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckToken {
}
3.定义切面
@Aspect
@Component
public class CheckTokenAspect {
// Service层切点 ,加了@CheckUserToken这个注解的方法都是切入点
@Pointcut("@annotation(com.common.util.annotation.CheckToken)")
public void servicePointcut() {}
// 切点方法执行前运行
@Before(value = "servicePointcut()")
public void doBefore(JoinPoint joinPoint) {
//1.获取token
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String token=request.getHeader("Authorization");
//判断token
if(StringUtils.isNotBlank(token)){
//解析token,这里没有写token解析的具体方法
}else{
throw new RuntimeException("token 不能为空!");
}
}
}