如何访问JAX-RS Application impl。来自Filter?

时间:2015-03-26 23:59:09

标签: annotations glassfish jersey jax-rs

我创建了JAX-RS @NameBinding注释:

@Retention(RUNTIME)
@NameBinding
public @interface EnableMyFilter {
    @Nonbinding
    String value() default "";
}

并使用它来激活过滤器,它会检查@EnableMyFilter注释的值。这部分对我来说至关重要,因为创建单独的注释和过滤器会产生很多样板代码。过滤代码:

@Provider
@EnableMyFilter
public class MyFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        final ExtendedUriInfo extendendUriInfo = (ExtendedUriInfo) requestContext.getUriInfo();

        Method method = extendendUriInfo.getMatchedResourceMethod().getInvocable().getHandlingMethod();
        RestrictedEnvironment annotation = method.getAnnotation(EnableMyFilter.class); // get method-level annotation
        if (annotation == null) {
            annotation = method.getDeclaringClass().getAnnotation(EnableMyFilter.class); // get class-level annotation
            if (annotation == null) {
                // here application-level annotation should be get
            }
        }

        // do something with annotation value...
    }
}

正如您所看到的,我使用Jersey特定的ExtendedUriInfo来反映方法并获取注释(如建议的here),如果失败,则从类中获取注释。但@NameBinding也可以在应用程序级别完成,例如:

@ApplicationPath("/")
@EnableMyFilter("some-val")
public class RestApplication extends Application {
}

并且此应用程序类提供程序也将被触发 - 这是100%好。但是如何在filter()中获得此类注释?

我试图注入@Context

@Context
private Application application;

但是application.getClass().toString()会返回org.glassfish.jersey.server.ResourceConfig$WrappingResourceConfig(我所理解的)没有注释。

我正在使用Glassfish 4.1 build 13,Java 8。

0 个答案:

没有答案