是否有可能在 Springboot 中有两个不同的 @RestControllers 使用不同的 MappingJackson2HttpMessageConverter ? ...还是 MappingJackson2HttpMessageConverter 是 spring boot 应用程序中所有 @RestController 通用的?
基本上,目标是使用包含不同 Jackson ObjectMapper 的不同 MappingJackson2HttpMessageConverter,它使用 Jackson MixIn 在第二个 Controller 中将 id 重命名(在 Json 中)为 priceId。
调用第一个 Controller 会做什么:
http://localhost:8080/controller1/price
{ id: "id", description: "描述"}
调用第二个 Controller 会做什么:
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:
最佳答案
MappingJackson2HttpMessageConverter
对于所有使用 @RestController
注释的 Controller 都是通用的,但是有一些方法可以解决这个问题。一个常见的解决方案是将 Controller 返回的结果包装到标记类中并使用自定义 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
传输对象使用自定义序列化程序。
关于java - 2个具有不同配置的@RestControllers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45599021/