Java (Jersey 2 + Grizzly 2) 端点的 JAX-RS 自定义资源注释?

Java (Jersey 2 + Grizzly 2) JAX-RS custom resource annotations for endpoints?

我想用某种 "roles" 属性来注释我的所有 JAX-RS 资源,访问控制过滤器将通过上下文读取该属性。这种 JAX-RS 资源的一个例子是 (psuedo):

@Path("foo")
public class FooResource {

    @GET
    @Context(roles = "admin,user")
    public Response foo() {
      return Response.noContent().build();
    }
}

因此,AccessControlFilter 可以访问资源特定的 "roles" 值:

public class AccessControlFilter {
  @Override
  public void filter(ContainerRequestContext context) throws IOException {
    String accessToken = accessToken(context);
    String roles = context.getContext("roles");    

    // ... validate access Token against roles ...

  }

  @Nullable
  private static String accessToken(ContainerRequestContext context) {
    Map<String, Cookie> cookies = context.getCookies();
    Cookie accessTokenCookie = cookies.get("access_token");
    if (accessTokenCookie != null) {
      return accessTokenCookie.getValue();
    }
    return null;
  }
}

我一直在四处挖掘:

只需将 ResourceInfo 注入过滤器 class。从那里您可以获得资源 Method。然后只需使用一些反射来获取注释。

@Context
private ResourceInfo resourceInfo;

@Override
public void filter(...) {
    Method method = resourceInfo.getResourceMethod();
    MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
    if (anno != null) {
        String roles = anno.value();
    }
}