Richard Sand
Richard Sand

Reputation: 674

In JAXRS apply a container request interceptor to a specific provider only

With JAXRS-2.0 (Jersey 2.2, specifically) I'm trying to apply a request interceptor to a specific resource provider class (which is in a 3rd party library), and I'm obviously doing it wrong. I am getting the error below - I'm a bit baffled as to the cause. The net effect is that the interceptor is being invoked on every request to every provider instead of the 1 provider. This is the error:

2017-11-26 10:43:51.061 [localhost-startStop-1][WARN][o.g.j.server.model.ResourceMethodConfig] - The given contract (interface javax.ws.rs.container.DynamicFeature) of class com.idfconnect.XYZ provider cannot be bound to a resource method.

The interceptor class is defined as:

@Provider
public class XYZ implements WriterInterceptor, DynamicFeature {

In my ResourceConfig I'm registering the interceptor for the specific provider as follows (I suspect this is where I've gone astray):

@ApplicationPath("service")
public class MyApp extends ResourceConfig {
  public MyApp() {
    ResourceConfig rc = register(SomeThirdPartyResource.class);
    rc.register(XYZ.class);
    ...

Can someone help me figure out how to bind the interceptor to SomeThirdPartyResource class only?

Upvotes: 0

Views: 703

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208964

You shouldn't make your provider implement DynamicFeature. This is probably the cause of the warning. You are trying to register the interceptor, which is also a DynamicFeature, and Jersey is telling you that DynamicFeature is not something that is supposed to be registered to a method.

You should make a separate class for the DynamicFeature and inside the configure check for the resource you want to attach your provider to (using the ResourceInfo, then register it accordingly. For example

class XYZ implements DynamicFeature {
    @Override
    public void configure(ResourceInfo info, FeatureContext ctx) {
       if (info.getResourceClass().equals(ThirdPartyResource.class) {
           ctx.register(YourWriterImplementation.class);
           // or
           ctx.register(new YourWriterImplementation());
       }
    }
}

The reason you are getting all the resources hit by the interceptor is because you are registering the interceptor with the ResourceConfig. This will attach it all resources. You only want to register the DynamicFeature and let it determine which resource to tie to.

Upvotes: 1

Related Questions