Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jax-rs ContextResolver<T> undestanding

But I was trying to understand the usage of Providers in jax-rs. But was not able to understand how ContextResolver can be used. Can someone explain this with some basic example?

like image 358
Jayendra Gothi Avatar asked Sep 09 '15 11:09

Jayendra Gothi


People also ask

What is ContextResolver?

public interface ContextResolver<T> Contract for a provider that supplies context information to resource classes and other providers. A ContextResolver implementation may be annotated with Produces to restrict the media types for which it will be considered suitable.

What is a JAX-RS provider?

The JAX-RS specification allows you to plug in your own request/response body reader and writers. To do this, you annotate a class with @Provider and specify the @Produces types for a writer and @Consumes types for a reader. You must also implement a MessageBodyReader/Writer interface respectively.

What is JAX-RS stackoverflow?

JAX-RS is a specification for RESTful Web Services with Java.


1 Answers

You will see it being used a lot in resolving a serialization context object. For example an ObjectMapper for JSON serialization. For example

@Provider
@Produces(MediaType.APPLICATION_JSON)
public static JacksonContextResolver implements ContextResolver<ObjectMapper> {
    private final ObjectMapper mapper;

    public JacksonContextResolver() {
        mapper = new ObjectMapper();
    }

    @Override
    public ObjectMapper getContext(Class<?> cls) {
        return mapper;
    }
}

Now what will happen is that the Jackson provider, namely JacksonJsonProvider, when serializing, will first see if it has been given an ObjectMapper, if not it will lookup a ContextResolver for the ObjectMapper and call getContext(classToSerialize) to obtain the ObjectMapper. So this really is an opportunity, if we wanted to do some logic using the passed Class to determine which mapper (if there are more than one) to use for which class. For me generally, I only use it to configure the mapper.

The idea is that you can lookup up arbitrary objects basic on some context. An example of how you would lookup the ContextResolver is through the Providers injectable interface. For example in a resource class

@Path("..")
public class Resource {
    @Context
    private Providers provider;

    @GET
    public String get() {
        ContextResolver<ObjectMapper> resolver
            = providers.getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON);
        ObjectMapper mapper = resolver.getContext(...);
    }
}
like image 114
Paul Samsotha Avatar answered Sep 21 '22 20:09

Paul Samsotha