【问题标题】:2 @RestControllers with different configurations2 个不同配置的@RestControllers
【发布时间】:2018-01-17 20:03:35
【问题描述】:

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

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

调用第一个控制器会做什么:

http://localhost:8080/controller1/price

{ id: "id", description: "描述" }

调用第二个控制器会做什么:

http://localhost:8080/controller2/price

{ priceId: "id", description: "描述" }

问候

@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

【问题讨论】:

标签: java spring spring-mvc spring-boot


【解决方案1】:

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

可以为您的Price 传输对象使用自定义序列化程序,而不是使用PropertyNamingStrategy

【讨论】:

    猜你喜欢
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多