I am using XmlMapper from com.fasterxml.jackson.dataformat.xml.
The class, I am serializing, has an Autowired member that is not serialized.
I want to be able to deserialize the XML into an instance and have the autowired member variable populated by Spring.
Is there a way to do this?
ObjectMapperhas setInjectableValues method which allow to register some external beans which we want to use duringserialisation/deserialisation. For example,DeserializationContextclass has findInjectableValue method which allow to find previously registered bean in context by name. Below you can find example which shows general idea how to do that. First, declare an injectable bean which we want to autowire:POJOclass which we want to deserialise fromXMLcould look like below:Now, we need to implement custom deserialiser which will inject autowired field:
Above deserialiser could be used only for
Pojoclass. If you need to do the same for many classes you can extractsetDependencymethod to an interface and implement it this interface by eachPOJOyou need to handle in the same way. In above deserialiser instead of casting toPojoyou can cast to your interface. To register our custom deserialiser I will useBeanDeserializerModifierbut you can do that in other way. For example if you already have custom deserialiser and you use@JsonDeserializeannotation you do not need to do that. Simple usage could look like below:For below
XMLpayload:Prints:
See also: