Spring-AOP之工作实践(一)

案例一、角色校验

  项目中,对某些方法需要用户具备指定角色权限才能执行。

/** 
 * 角色校验注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HasRole {
    String[] value() default {};
}
/**
 * 角色校验切面
 */
@Component
@Aspect
@Order(0)
public class RoleAspect {
    @Autowired
    private UserService userService;

    // 切入点
    @Pointcut("@annotation(com.demo.annotation.HasRole)")
    private void pointCut() {}

    // 前置通知,在执行目标方法之前执行
    @Before("pointCut()")
    public void checkRole(Joinpoint joinpoint) {
        Signature signature = joinpoint.getSignature();
        MethodSignature methodSignature = null;
        // 判断注解作用对象是否为方法
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        methodSignature = (MethodSignature) signature;
        // 获取当前访问的class
        Class<?> className = joinpoint.getTarget().getClass();
        // 获取当前访问的方法名
        String methodName = methodSignature.getName();
        // 获取当前访问的方法形参类型
        Class[] argClass = methodSignature.getParameterTypes();
        // 获取当前访问的方法对象
        Method method = className.getMethod(methodName, argClass);
        // 获取当前访问的方法上的注解
        HasRole hasRole = method.getAnnotation(HasRole.class);
        // 校验权限,去数据库查是否有该权限
        if (!userService.hasRole(hasRole.value())) {
            // 抛出自定义权限异常
            throw new AuthorizationException("无权限");
        }
    }
}
/**
 * 目标对象
 */
@Controller
public class DemoController {
    // 目标方法,NeedRole:定义了角色权限的枚举类
    @PostMapping
    @HasRole("NeedRole.ADMIN")
    public void demoMethod(String arg) {
        System.out.println("角色校验");
    }
}

 

posted @ 2020-06-09 17:34  玉壶冰  阅读(163)  评论(0编辑  收藏  举报