使用AOP实现鉴权系统
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
1.注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HasRight {
String value() default "";
}
2.AOP
@Aspect
@Component
public class Right { //不会检验内部openfeign请求 哦
@Before("@annotation(com.czh.right.anno.HasRight)")
public void beforeMethod(JoinPoint joinPoint){
System.out.println("============>AOP");
Signature signature = joinPoint.getSignature();
try {
String name = signature.getName();//方法名
String declaringTypeName = signature.getDeclaringTypeName();// 类名
Class<?> aClass = Class.forName(declaringTypeName);//反射拿到类
Method method = aClass.getMethod(name);
HasRight annotation = method.getAnnotation(HasRight.class);//拿到方法上的注解信息
HttpServletRequest request = RequestUtil.getRequest();
System.out.println(request.getRequestURL());
String token = request.getHeader("token");
System.out.println(token);
System.out.println(annotation.value());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("进入方法前");
}
}
3. 使用
@RestController
@RequestMapping("system")
public class TestController {
@GetMapping("t1")
@HasRight("all")
public String test(){
return "Helloworld";
}
}
于是乎 你就可以在AOP切面中搞事情了。比如验证 request中携带的权限信息 对比是否符合权限 没有此权限直接返回