5

Is it possible to have two different @RestControllers that use different MappingJackson2HttpMessageConverter in Springboot ? ... or is the MappingJackson2HttpMessageConverter common for all @RestController in a spring boot application ?

Basically, the goal would be to use a different MappingJackson2HttpMessageConverter containing a different Jackson ObjectMapper that uses a Jackson MixIn to rename(in the Json) the id to priceId in the 2nd Controller.

What a call to the first controller would do :

http://localhost:8080/controller1/price

{ id: "id", description: "Description" }

What a call to the second controller would do :

http://localhost:8080/controller2/price

{ priceId: "id", description: "Description" }

Regards

@SpringBootApplication
public class EndpointsApplication {

public static void main(String[] args) {
    SpringApplication.run(EndpointsApplication.class, args);
}

@Data // Lombok
@AllArgsConstructor
class Price {
    String id;
    String description;
}

@RestController
@RequestMapping(value = "/controller1")
class PriceController1 {

    @GetMapping(value = "/price")
    public Price getPrice() {
        return new Price("id", "Description");
    }
}

@RestController
@RequestMapping(value = "/controller2")
class PriceController2 {

    @GetMapping(value = "/price")
    public Price getPrice() {
        return new Price("id", "Description");
    }
}

}

GitHub:

https://github.com/fdlessard/SpringBootEndpoints

  • 1
    Please have a look https://stackoverflow.com/questions/34728814/spring-boot-with-two-mvc-configurations this post. – Akash Aug 09 '17 at 19:23

1 Answers1

4

The MappingJackson2HttpMessageConverter is common for all controller annotated with @RestController, nevertheless there are ways around this. A common solution is wrapping the result returned by your controller into a marker class and using a custom MessageConverter (Example implementation used by Spring Hateoas) and/or using a custom response media type.

Sample usage of TypeConstrainedMappingJackson2HttpMessageConverter where ResourceSupport is the marker class.

MappingJackson2HttpMessageConverter halConverter = 
    new TypeConstrainedMappingJackson2HttpMessageConverter(ResourceSupport.class);
halConverter.setSupportedMediaTypes(Arrays.asList(HAL_JSON));
halConverter.setObjectMapper(halObjectMapper);

You can find a working example based on your code here: https://github.com/AndreasKl/SpringBootEndpoints

Instead of using a PropertyNamingStrategy a custom serializer can be used for your Price transfer object.

Andreas
  • 5,251
  • 30
  • 43