5

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?

svarog
  • 9,477
  • 4
  • 61
  • 77
Jayendra Gothi
  • 682
  • 2
  • 11
  • 26

1 Answers1

6

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(...);
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • That was nice example. isn't it can be used as factory to produce objects depending on the input. – Jayendra Gothi Sep 09 '15 at 12:21
  • 1
    You can read the explanation in [the spec 4.3 Context Providers](https://jsr311.java.net/nonav/releases/1.1/spec/spec.html). It doesn't go into great detail about _what_ it should be used for, so I imagine it's for general purpose use. If you can make it work, then use it I guess. – Paul Samsotha Sep 09 '15 at 14:04
  • 1
    I haven't been able to find any documentation that states what type of object should be returned from a `ContextResolver` for a particular content type, but I did find this comment in the RestEasy docs: ["You should not use this feature unless you know what you're doing."](https://docs.jboss.org/resteasy/docs/4.3.1.Final/userguide/html/Built_in_JAXB_providers.html#Pluggable_JAXBContext_s_with_ContextResolvers) – iboisver Oct 09 '19 at 02:40