如何在JAX-RS运行时中控制@Provider

时间:2015-01-11 07:41:41

标签: java jackson jax-rs

我在我的JAX-RS应用程序中使用了自定义的ContextResolver。

@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Provider
public class ObjectMapperContextResolver
    implements ContextResolver<ObjectMapper> {

    public ObjectMapperContextResolver() {
        super();
        // I want to control this
        objectMapper = new ObjectMapper()
            .configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
        objectMapper.registerModule(new JaxbAnnotationModule());
    }

    @Override
    public ObjectMapper getContext(final Class<?> type) {
        return objectMapper;
    }

    private final ObjectMapper objectMapper;
}

如您所见,有一个选项(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME)已定制。

如何在JAX-RS资源中按需关闭该选项?

@Path("/items")
public class ItemsResource {

    @GET
    @Produces({APPLICATION_JSON, APPLICATION_XML})
    public Response read(@QueryParam("wrap") final boolean wrap) {
        if (wrap) {
            // turn off MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME
            // and then return response of [Items]
        } else {
            // turn on MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME
            // and then return response of [List<Item>]
        }
    }
}

有没有办法注入提供者?

0 个答案:

没有答案