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?
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.
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.
JAX-RS is a specification for RESTful Web Services with Java.
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(...);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With