为什么@Provider注释不起作用? (目标是将模块附加到ObjectMapper单例)
根据JavaDocs
默认构造函数,通常在将提供者自动配置为与JAX-RS实现一起使用时使用。
当使用空构造函数调用JacksonJsonProvider时,
public JacksonJsonProvider() {
this((ObjectMapper)null, BASIC_ANNOTATIONS);
}
ObjectMapper仅设置为null。 BASIC_ANNOTATIONS可能包含@Provider
。
在Blueprint将类初始化到内存中之后,一定有可能设置ObjectMapper。
所以我有两个选择:
看起来
protected ObjectMapper _locateMapperViaProvider
蓝图
<cxf:rsServer id="cxfConsumer" address="/" serviceClass="com.domain.MyServiceInterface">
<cxf:providers>
<ref component-id="jsonProvider"/>
</cxf:providers>
</cxf:rsServer>
<bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider">
我的@Provider类
@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class JacksonObjectMapperProvider implements ContextResolver<ObjectMapper> {
final ObjectMapper defaultObjectMapper;
public JacksonObjectMapperProvider() {
this.defaultObjectMapper = makeObjectMapper();
}
@Override
public ObjectMapper getContext(Class<?> type) {
return defaultObjectMapper;
}
private static ObjectMapper makeObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new MyObjectSerializerModule());
return mapper;
}
}
我的序列化器
public class MyObjectSerializerModule extends SimpleModule {
public MyObjectSerializerModule() {
super("ObjectIdSerializerModule", new Version(1, 0, 0, "alpha"));
this.addSerializer(MyObject.class, new MyObjectSerializer());
}
public class MyObjectSerializer extends JsonSerializer<Location> {
@Override
public void serialize(MyObject value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("id", value.getId());
jsonGenerator.writeEndObject();
}
}
}
答案 0 :(得分:0)
看来答案是“不,先生”。
就我所知,@Provider注释不起作用。在初始化期间,必须在CXF中注入/注册提供程序。我欢迎您提出其他答案。
<cxf:rsServer id="cxfConsumer" address="/" serviceClass="com.domain.MyServiceInterface">
<cxf:providers>
<ref component-id="jsonProvider"/>
<ref component-id="JacksonObjectMapperContextProvider"/>
</cxf:providers>
</cxf:rsServer>
<bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider">
<bean id="jsonProvider" class="JacksonObjectMapperContextProvider">