Search code examples
jakarta-eejax-rsresolver

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?


Solution

  • 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(...);
        }
    }