1

Is there any way to automatically register a ClientResponseFilter without using register() method on a WebTarget or Client? I'm looking for something simillar to the @Provider annotation which can be used only in a ContainerResponseFilter/ContainerRequestFilter.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Jakub
  • 69
  • 7

1 Answers1

1

Unfortunately there are no scanning capabilities implemented in the client side. The closest thing you will get to automatic registration is with the use of SPIs (Service Provider Interfaces). Any SPI supported will be specific to the JAX-RS implementation. In this post, you can see how a MessageBodyReader may be implemented as an SPI, and a JAX-RS implementation may automatically register it.

As mentioned though, it is up to the JAX-RS implementation to decide what SPIs it wants to support. With Jersey, the most generic SPI is the AutoDisoverable.

public interface AutoDiscoverable {
    public void configure(FeatureContext context);
}

You just implement this interface, registering any providers you want with the FeatureContext. Then you create a file

/META-INF/services/org.glassfish.jersey.internal.spi.AutoDiscoverable

and just put the fully qualified name of your implementation into that file. The Jersey runtime will discover this file and call your configure() method.

One example of the AutoDiscoverable is the JacksonAutoDiscoverable. And the SPI file. When we add the jersey-media-json-jackson dependency to our project, Jersey will find the SPI implementation of the AutoDiscoverable and will call the configure() method, which registers the JacksonFeature, so we don't need to manually register it ourselves.

The use of the auto-discoverable, or most SPIs in general, is for use with reusable libraries. Usually for a project where your provider is used only for that specific project, adding the auto-discovery capabilities to the provider just adds unnecessary work. It's easier to just register the provider manually. But if you want to create a library that can be reused, and you want the user to not have to explicitly register any providers or features, then you might want to implement the auto-discovery.


Some more details

If you are going to implement the AutoDiscoverable, one thing I should mention is that we can put a constraint on which runtime it should be applied to; client or server, We do that with the @ConstrainedTo annotation.

@ConstrainedTo(RuntimeType.CLIENT)
public class MyAutoDiscoverable implements AutoDiscoverable {}

If your AutoDiscoverable registers a ClientRequestFilter, then you wouldn't want the server to register this, so you would constrain to the client runtime.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720