我将 Spring MVC 3.0.5 与 Jackson 1.7.2 一起使用。
我希望实现一个动态 Bean 序列化程序分配机制,例如,假设我的 MVC 控制器返回 ( @ResponseBody
) 一个 MyObject 类型的对象。默认情况下,Jackson 的 SerializerFactory 将寻找最合适的序列化器,包括我的自定义序列化器(例如CustomSerializer extends JsonSerializer<MyObject>
)。
但是,我希望触发我的自定义序列化程序,以防万一某些标志处于活动状态(比如说,附加到 ThreadLocal 的布尔变量)。否则,我想使用 Jackson 提供MappingJacksonHttpMessageConverter
的序列化器,保持默认行为不变。
有什么方法可以实现吗?
我已经将我自己的 ObjectMapper、SerializerFactory 和 CustomSerializers 注册到 Spring 的<mvc:annotaion-driven />
defaultMappingJacksonHttpMessageConverter
中。
public class ConvertingPostProcessor implements BeanPostProcessor {
private ObjectMapper jacksonJsonObjectMapper;
public Object postProcessBeforeInitialization(Object bean, String name)
throws BeansException {
if (bean instanceof AnnotationMethodHandlerAdapter) {
HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
for (HttpMessageConverter<?> conv: convs) {
if (conv instanceof MappingJacksonHttpMessageConverter) {
((MappingJacksonHttpMessageConverter) conv).setObjectMapper(jacksonJsonObjectMapper);
}
}
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name)
throws BeansException {
return bean;
}
public void setJacksonJsonObjectMapper(ObjectMapper jacksonJsonObjectMapper) {
this.jacksonJsonObjectMapper = jacksonJsonObjectMapper;
}
}
spring-mvc.xml 将是:
<mvc:annotation-driven />
...
<bean id="jacksonJsonObjectMapper" class="org.mycode.serialize.CustomObjectMapper">
<property name="customSerializerFactory" ref="jacksonJsonCustomSerializerFactory" />
</bean>
<bean id="jacksonJsonCustomSerializerFactory" class="org.mycode.serialize.CustomSerializerFactoryRegistry">
<property name="serializers">
<map>
<entry key="org.mycode.domain.MyObject" value-ref="customSerializer" />
</map>
</property>
</bean>
<bean id="customSerializer" class="org.mycode.serialize.CustomSerializer">
<property name="jacksonJsonCustomSerializerFactory" ref="jacksonJsonCustomSerializerFactory" />
</bean>
<bean id="convertingPostProcessor" class="org.mycode.serialize.ConvertingPostProcessor">
<property name="jacksonJsonObjectMapper" ref="jacksonJsonObjectMapper" />
</bean>
提前致谢!!