我创建了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。