自定义注解使用AOP做权限校验
你好,我是程序员Alan, 很高兴遇见你。
最近看 RocketMQ 源码时,发现它是使用自定义注解的方式做权限校验,蛮有意思的,于是简单上手试了一下。
下面是部分代码。
自定义注解
import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Permission { String permission() default ""; }
编写切面
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import org.aspectj.lang.reflect.MethodSignature; @Component @Aspect public class PermissionAnnotationAspect { @Pointcut("@annotation(com.esandinfo.pclogin.permission.Permission)") private void permission() { } @Around("permission()") public void advice(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); if (!method.isAnnotationPresent(Permission.class)) { joinPoint.proceed(); //没有使用注解默认放行 } else { Permission permission = fetchPermission(methodSignature); //[1] 取出请求方的权限信息 String userPermission = "TEST"; //假设用户权限为 TEST System.out.println("用户权限: " + userPermission); //[2] 和注解的值做比较 permission.permission() if (userPermission.equals(permission.permission())){ //[3] 校验通过放行用户 System.out.println("放行"); joinPoint.proceed(); } return; } } private Permission fetchPermission(MethodSignature methodSignature) { return methodSignature.getMethod().getAnnotation(Permission.class); } }
测试
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PermissionAnnotationController { @RequestMapping(value = "/public/testMethod") @Permission(permission = "TEST") public void testMethod(){ } }
测试结果