控制
一、自定義注解
1.1 定義注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Access {
String[] value() default {};
}
1.2 使用注解
@RestController
public class TestController {
@Access(value = {"admin"})
@GetMapping("/test")
public String test(){
return "test";
}
}
二、AOP實現接口訪問權限控制
2.1 定義切面
@Aspect
@Component
public class AccessAspect {
@Pointcut("@annotation(com.example.demo.annotation.Access)")
public void access() {
}
@Before("access()")
public void doBefore(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Access access = method.getAnnotation(Access.class);
if (access == null) {
return;
}
String[] values = access.value();
// 校驗用戶是否有權限
// ...
}
}
2.2 啟用AOP
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}