Search code examples
javaspringspring-bootjacksonjson-deserialization

Autowiring Beans in Custom instance of Jackson StdDeserializer


I have a request object using a custom deserializer for a member of object

@JsonDeserialize(using = SomeClassDeserializer.class)
private SomeClass someClass;

Spring Boot does not autowire annotated fields by default even if the class is annotated with @Component because Jackson handles the instantiation. How do I work around preserving the default constructors needed by Jackson, and injecting beans for use in the Deserializer?


Solution

  • I found the answer lies with a third constructor using the conventional @Autowired annotation and injecting the required bean this way. However, instead of using the typical instance of member assignment, declare the field as static and assign this injected bean to all instances of the deserializer generated by Jackson. It's kind of a hacky workaround, but it solved issue for me.

    public class SomeClassDeserializer extends StdDeserializer<SomeObject> {
        private static SomeUtil someUtil;
    
        public SomeClassDeserializer(Class<?> vc) {
            super(vc);
        }
    
        public SomeClassDeserializer() {
            this(null);
        }
    
        @Autowired
        public SomeClassDeserializer(SomeUtil someUtil) {
            this(null);
            SomeClassDeserializer.someUtil= someUtil;
        }