andrewdleach
andrewdleach

Reputation: 2466

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?

Upvotes: 0

Views: 2024

Answers (2)

Ishika Garg
Ishika Garg

Reputation: 1

public class SomeClassDeserializer extends StdDeserializer<SomeObject> {

    @Autowired
    private  SomeUtil someUtil;

    public SomeClassDeserializer(Class<?> vc) {
        super(vc);
    }

    public SomeClassDeserializer() {
        this(null);
    }

  /*  @Autowired
    public SomeClassDeserializer(SomeUtil someUtil) {
        this(null);
        SomeClassDeserializer.someUtil= someUtil;
    }*/

I have a question as to why we cannot do this instead of the answer above

Upvotes: 0

andrewdleach
andrewdleach

Reputation: 2466

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;
    }

Upvotes: 3

Related Questions