Get resource class annotation values inside ContainerRequestFilter

不问归期 提交于 2019-11-27 14:46:34

Look at this in your filter

Class<?> clazz = this.getClass();
FortressProtected annotation = clazz.getAnnotation(FortressProtected.class);

this.getClass() corresponds to the filter class (whose annotation has no values). You instead need to get the annotation on the ResourceImpl

A couple options. You could explicitly use ResourceImpl.class.getAnnotation(...). But the problem with this is that once you bind more than one class, how do you match which class corresponds to which request. For that reason, the next option is more viable.

What you do is inject ResourceInfo. With this, you can call it's getResourceMethod or getResourceClass methods. These methods return the matched method and class, respectively. You could then check for the annotation at the class level as well as the method level (as we are also allowed to bind at the method level). So you might have something more like:

@Provider
@FortressProtected
public class FortressAuthorizer implements ContainerRequestFilter {

  @Context
  ResourceInfo resourceInfo;

  @Override
  public void filter(ContainerRequestContext requestContext) throws IOException {

    Class<?> resourceClass = resourceInfo.getResourceClass();
    FortressProtected classAnnot = resourceClass.getAnnotation(FortressProtected.class);
    if (classAnnot != null) {
      // do something with annotation
    }

    Method resourceMethod = resourceInfo.getResourceMethod();
    FortressProtected methodAnnot = resourceMethod.getAnnotation(FortressProtected.class);
    if (methodAnnot != null) {
      // do something with annotation
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!