Spring RestController每个方法的AOP自定义访问规则

时间:2015-10-01 10:39:53

标签: java spring rest aop

我有一个API类,其中有几种方法具有不同的访问规则要求,例如:只有组中的用户才能访问此API,或者此API允许未经身份验证的访问。

在Spring中处理此问题的最佳做法是什么?

我希望使用AOP通过自定义注释来处理这个问题,但在调查之后似乎并不可能。 e.g。

@RequestMapping("/getGroup")
@GroupMembersOnly

1 个答案:

答案 0 :(得分:0)

我现在就开始工作了。

注释

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Inherited
@Documented
public @interface GroupMembersOnly {

}

我的配置类中缺少的部分

@Aspect
public class AopConfiguration{
...
@Around("execution(* *(..)) && @annotation(groupMembersOnly)")
  public Object around(ProceedingJoinPoint point, GroupMembersOnly groupMembersOnly) throws Throwable {

    //do something, e.g. use point.getArgs()
    //to do something with the menthod arguments

    //give control back to method
    return point.proceed();
}
}

然后我想截取的方法

@RequestMapping("/getGroup")
@GroupMembersOnly
public ResponseEntity<List<String>> readMembers(HttpServletRequest request, HttpServletResponse response) {
/*Add HttpServletRequest request, HttpServletResponse response arguments if you 
want to do something with them in the interceptor*/