jax-rs ContextResolver<T> undestanding

泪湿孤枕 提交于 2019-12-23 17:17:48

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/32478159/jax-rs-contextresolvert-undestanding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!