Is there a way to use JAX-RS annotated interface with Jersey as the client?

James picture James · Jun 12, 2013 · Viewed 7.8k times · Source

Given that I have an interface which represents my RESET service using

public interface BookResource {

     @GET
     @Path("/book/isbn/{isbn}/")
     @Produces(value = { MediaType.APPLICATION_XML })
     public ClientResponse<Book> getBookByIsbn(@PathParam("isbn") String isbn, @QueryParam("releaseStatus") String releaseStatus);

}

How can I create a proxy to the actual service implementation if I am required to use Jersey as the JAX-RS provider/REST framework in my webapp.

This is easy to do with RESTEasy/Spring integration and means I can use my JAX-RS interface directly without having to wrap it and right boiler plate to do the invocation.

Basically I'm looking for a Jersey equivalent to the following: -

<bean id="bookResource" class="org.jboss.resteasy.client.spring.RestClientProxyFactoryBean">
    <property name="serviceInterface" value="my.company.book.service.BookResource" />
    <property name="baseUri" value="http://localhost:8181/books-service/" />
</bean>

I've just spent the last hour googling this and keep getting back to the standard client API in Jersey which seems to require a lot of boiler plate to achieve the same. Can anyone point me in the right direction?

Answer

Dmytro picture Dmytro · Oct 10, 2013

This link seems to be more practical: http://blog.alutam.com/2012/05/04/proxy-client-on-top-of-jax-rs-2-0-client-api/

// configure Jersey client
ClientConfig cc = new ClientConfig().register(JacksonFeature.class)
            .register(AnotherFeature.class)
            .register(SomeFilter.class);
Client resource = ClientBuilder.newClient(cc);
// create client proxy
ServiceInterface proxy = WebResourceFactory.newResource(ServiceInterface.class,
            resource.target(ServiceURI));

// invoke service
MyType result = proxy.someMethod();

For maven project you would need following dependencies:

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-proxy-client</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>${jersey.version}</version>
    </dependency>