My question is essentially the same as this one: How can I get resource annotations in a Jersey ContainerResponseFilter.
But I\'m using Java Jersey 2.4 and can\'t fi
If you want to modify processing of a request based on annotations available on a resource method/class then I'd recommend using DynamicFeature from JAX-RS 2.0. Using DynamicFeature
s you can assign specific providers for a subset of available resource methods. For example, consider I have a resource class like:
@Path("helloworld")
public class HelloWorldResource {
@GET
@Produces("text/plain")
public String getHello() {
return "Hello World!";
}
}
And I'd like to assign a ContainerRequestFilter to it. I'll create:
@Provider
public class MyDynamicFeature implements DynamicFeature {
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
if ("HelloWorldResource".equals(resourceInfo.getResourceClass().getSimpleName())
&& "getHello".equals(resourceInfo.getResourceMethod().getName())) {
context.register(MyContainerRequestFilter.class);
}
}
}
And after registration (if you're using package scanning then you don't need to register it in case it has @Provider
annotation on it) MyContainerRequestFilter
will be associated with your resource method.
On the other hand you can always inject ResourceInfo in your filter (it can't be annotated with @PreMatching
) and obtain the annotations from it:
@Provider
public class MyContainerRequestFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
resourceInfo.getResourceMethod().getDeclaredAnnotations();
}
}