0

Here's the setup I have:

A RestTemplate with custom MessageConverter's ObjectMapper that has some deserialization features and problem handlers (Jackson Fasterxml 2.8.9). The RestTemplate also has a custom ResponseErrorHandler.

During a REST call with RestTemplate, if the response status needs to be handled by ResponseErrorHandler, I might have to parse the stream body and map it to an object.

I was wondering, if I can make my ObjectMapper a bean (@Bean/@Qualifer), would I be able to use this singleton bean in both RestTemplate's ObjectMapper, and inject it as dependency into the same RestTemplate's ResponseErrorHandler? Would that be safe?

The reason I want to do this is that all the deserialization features and problem handlers should be the identical when it comes to data binding -- whether it happens inside RestTemplate data extraction mechanism or when the response body needs to be mapped during ResponseErrorHandler#handlerError().

NuCradle
  • 665
  • 1
  • 9
  • 31
  • Possible duplicate of [What is the advantage of declaring ObjectMapper as a bean?](https://stackoverflow.com/questions/50362883/what-is-the-advantage-of-declaring-objectmapper-as-a-bean) – Mạnh Quyết Nguyễn Sep 11 '19 at 02:38
  • The context of this question is different. One must iterate through all the `MessageConverter`'s that `RestTemplate` provides to find the appropriate one and get its `ObjectMapper`. When `RestTemplate` extracts the data, internally it uses this `ObjectMapper`, so I am not sure in what state it is if it is used again inside the **same** `RestTemplate`'s custom `ResponseErrorHandler` before `RestTemplate`'s is returned. – NuCradle Sep 11 '19 at 02:51

1 Answers1

0

Define object mapper and RestTemplate bean.

Or manually RestTemplate each time you create it.

Remember to add the converter as the first converter in the list.

@Bean
public RestTemplate restTemplate() {
    RestTemplate rest = new RestTemplate();
    // Add the object mapper as first instance in list for eager discovery
    rest.getMessageConverters().add(0, jacksonConverter());
    return rest;
}

@Bean
public HttpMessageConverter jacksonConverter() {
    MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
    converter.setObjectMapper(objectMapper());
    return converter;
}

@Bean
public ObjectMapper objectMapper() {
    return new ObjectMapper();
}
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51
  • Yes, the question was, can I safely use that `@Bean ObjectMapper` inside of my **custom** `RestTemplate`'s `ResponseErrorHandler` to deserialize from the stream even though it's going to be the same bean object that `RestTemplate` uses for extraction of data (see `RestTemplate` [code here](https://github.com/spring-projects/spring-framework/blob/5.0.x/spring-web/src/main/java/org/springframework/web/client/RestTemplate.java#L690) -- note also line 691) – NuCradle Sep 11 '19 at 11:34