I am using Spring MVC 3.0.5 with Jackson 1.7.2.
I want to implement a dynamic mechanism for assigning a Bean serializer, for example, say that my MVC controller returns ( @ResponseBody ) an object of type MyObject. By default, Jackson SerializerFactory will search for the most suitable Serializer, including my custom Serializers (e.g. CustomSerializer extends JsonSerializer<MyObject> ).
However, I want my custom Serializers to run only if some flag is active (for example, a logical variable bound to ThreadLocal). Otherwise, I want to use the ones provided by the Jackson Seculator, while preserving the default MappingJacksonHttpMessageConverter behavior.
Is there a way to implement an approach to this?
I already registered my own ObjectMapper, SerializerFactory and CustomSerializers in Spring <mvc:annotaion-driven /> by default MappingJacksonHttpMessageConverter .
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; } }
And spring -mvc.xml will be:
<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>
Thanks in advance!
source share