jax-rs ContextResolver< T> undestanding [英] jax-rs ContextResolver<T> undestanding

查看:161
本文介绍了jax-rs ContextResolver< T> undestanding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

但我试图了解jax-rs中Providers的用法。但是无法理解如何使用ContextResolver。有人可以用一些基本的例子来解释这个吗?

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?

推荐答案

你会看到它在解析序列化上下文对象时被大量使用。例如,用于JSON序列化的 ObjectMapper 。例如

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;
    }
}

现在将会发生的是Jackson提供商,即 JacksonJsonProvider ,在序列化时,首先会看到它是否已被赋予 ObjectMapper ,如果没有,它将查找 ContextResolver 用于 ObjectMapper 并调用 getContext(classToSerialize)以获取 ObjectMapper 。所以这真的是一个机会,如果我们想使用传递的来做一些逻辑来确定哪个映射器(如果有多个)用于哪个类。对我来说,我只使用它来配置映射器。

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.

这个想法是你可以在某些上下文中查找基本的任意对象。如何查找 ContextResolver 的示例是通过 Providers 可注射界面。例如,在资源类中

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

这篇关于jax-rs ContextResolver&lt; T&gt; undestanding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆