Spring Boot 2.1.4: @Autowired does not work in custom Jackson Serializers/Deserializers, how to enable it?

Viewed 313

I am struggeling to get a Spring Component @Autowired into my custom Deserializer.

Example:

@JsonDeserialize (using = SomeClassJsonDeserializer.class)
SomeClass {
[...]
}

@JsonComponent
SomeClassJsonDeserializer extends JsonDeserializer<SomeClass> {

@Autowired
private SomeService service;

  @Override
      public SomeClass deserialize(JsonParser jsonParser,
              DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
     [...]
     // this.service is null
  }

}

I found mainly two possible solutions which didn't work for me at all:

  • use SpringBeanAutowiringSupport in default constructor of Deserializer
  • use HandlerInstantiator (via config / custom implementation)

I am using only those Jackson annotations shown in the example above to 'configure' the Jackson parsing. There is no additional custom configuration affecting Jackson in any way besides the default SpringBoot auto configuration. When using @EnableWebMvc (which breaks Spring-Boot auto configuration so I don't want to use it), the Component-wiring does work as expected.

Is there any official / recommended solution for plain Spring-Boot with default auto configuration ?

1 Answers

The problem was with how I used Spring's RestTemplate.

For a remote call, I created a new Instance of RestTemplate by contructor call (new RestTemplate()). This way, Spring wasn't able to configure the RestTemplate - bean correctly (so that SpringBoot autoconfigure and Jackson autoconfigure 'connect' together, resulting in working Spring-DI in custom Jackson components).

I simply had to @Autowire the RestTemplateBuilder bean instance provided by Spring, and then call RestTemplateBuilder.build() to aqquire a RestTemplate bean instance created by Spring.

Related