java - 2个具有不同配置的@RestControllers

标签 java spring spring-mvc spring-boot

是否有可能在 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:

https://github.com/fdlessard/SpringBootEndpoints

最佳答案

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/

相关文章:

java - Google V8 的工作方式与 Java 虚拟机类似吗?

spring - 使用 Java 配置时,Camel 的 BridgePropertyPlaceholderConfigurer 不工作

java - 如何使用 spring mvc void Controller 方法?

spring - IntelliJ 需要将 tomcat/conf 目录复制到项目目录

java - 从 HttpServletRequest 获取 AsyncContext

c# - 通过 C# 运行 weka

java - 使用 java 创建 xml

java - @ContextConfiguration 中配置类的初始化顺序会受到影响吗?

java - 将 Oauth 2.0 添加到基于 Jersey 的 RESTful 服务器

java - 无法理解 File object.delete() 的工作原理