2 @RestControllers with various configurations

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

Basically, the goal would be to use another MappingJackson2HttpMessageConverter containing another Jackson ObjectMapper that uses Jackson MixIn to rename (in Json) the priceId in the second controller.

What will the first controller call:

http: // localhost: 8080 / controller1 / price

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

What will cause the second controller:

http: // localhost: 8080 / controller2 / price

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

Hi

@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

+4
source share
1 answer

MappingJackson2HttpMessageConverteris common to all controllers annotated with help @RestController, however there are ways around this. A common solution is to transfer the result returned by your controller to the marker class and use a custom one MessageConverter (Example implementation used by Spring Hateoas) and / or using a custom type of media response.

Usage example TypeConstrainedMappingJackson2HttpMessageConverter, where ResourceSupportis the marker class.

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

, : https://github.com/AndreasKl/SpringBootEndpoints

PropertyNamingStrategy Price.

+3

Source: https://habr.com/ru/post/1683371/


All Articles