'How to add multiple deserializers in Spring controller?

I have a controller in my Spring application that needs to add multiple deserializers inside its ObjectMapper object. For this I have create 2 custom deserializer setup this way:

public class CustomDeserializer extends StdDeserializer<CustomObject> {

   public CustomDeserializer(Class<CustomObject> svip, ObjectMapper mapper) {
           super(svip);
           this.mapper = mapper;
   }

    public CustomDeserializer(ObjectMapper mapper) {
        this(null, mapper);
    }
    @Override
    public CustomObject deserialize(JsonParser jp, DeserializationContext deserializationContext) { 
        //uses global mapper object to deserialize  certain fields
    }
}

In my Controller, my constructor has a ObjectMapper and does this.mapper = mapper and also does the following inside the constructor function:

        SimpleModule module = new SimpleModule();
        module.addDeserializer(CustomObject.class, new CustomDeserializer(this.mapper));
        module.addDeserializer(CustomObject2.class, new CustomTwoDeserializer((this.mapper)));
        this.mapper.registerModule(module);

The reason I did it this way is to allow a single mapper to be used on multiple deserializers, however, I think there is an issue with instantiating a new deserializer in the constructor. Is there a proper way to not only share the same ObjectMapper initialized in the constructor of the controller but also not have to instantiate the deserializers in the constructor? My assumption is this will redundantly spawn more than 1 deserializer in a production environment rather than sharing the same one.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source