2 @RestControllers具有不同的配置

时间:2017-08-09 19:21:31

标签: java spring spring-mvc spring-boot

是否可以在Springboot中使用两个不同的 @RestControllers 使用不同的 MappingJackson2HttpMessageConverter ? ...或者是SpringJackCon应用程序在Spring启动应用程序中对所有@RestController通用吗?

基本上,目标是使用不同的MappingJackson2HttpMessageConverter,它包含一个不同的Jackson ObjectMapper,它使用Jackson MixIn在第二个控制器中重命名(在Json中)id到priceId。

对第一个控制器的调用是什么:

http://localhost:8080/controller1/price

{id:“id”,说明:“说明”}

对第二个控制器的调用是什么:

http://localhost:8080/controller2/price

{priceId:“id”,描述:“描述”}

此致

@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 个答案:

答案 0 :(得分:3)

MappingJackson2HttpMessageConverter对于使用@RestController注释的所有控制器都很常见,但是有很多方法可以解决这个问题。一个常见的解决方案是将控制器返回的结果包装到标记类中,并使用自定义MessageConverter (Example implementation used by Spring Hateoas)和/或使用自定义响应媒体类型。

TypeConstrainedMappingJackson2HttpMessageConverter的示例用法,其中ResourceSupport是标记类。

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

您可以在此处找到基于代码的工作示例: https://github.com/AndreasKl/SpringBootEndpoints

您的PropertyNamingStrategy传输对象可以使用自定义序列化工具,而非使用Price

相关问题